feat: migrate MCP runtime to TypeScript
This commit is contained in:
@@ -0,0 +1,44 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { existsSync, mkdtempSync, readFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import test from "node:test";
|
||||
import { clientConfig, runCli } from "../src/cli.js";
|
||||
import { VERSION } from "../src/version.js";
|
||||
|
||||
test("package, manifest, and runtime versions agree with no runtime npm dependencies", () => {
|
||||
const packageJson = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8"));
|
||||
const manifest = JSON.parse(readFileSync(new URL("../install-manifest.json", import.meta.url), "utf8"));
|
||||
assert.equal(VERSION, "0.3.0");
|
||||
assert.equal(packageJson.version, VERSION);
|
||||
assert.equal(manifest.version, VERSION);
|
||||
assert.deepEqual(packageJson.dependencies, undefined);
|
||||
assert.equal(manifest.runtime.runtimeNpmDependencies, 0);
|
||||
});
|
||||
|
||||
test("generated MCP config contains no Key, token, or environment secret", () => {
|
||||
const config = clientConfig("/private/config.json", false);
|
||||
const serialized = JSON.stringify(config);
|
||||
assert.match(serialized, /nocobase-crm/);
|
||||
assert.match(serialized, /config\.json/);
|
||||
assert.doesNotMatch(serialized, /authorize|token|secret|password/i);
|
||||
});
|
||||
|
||||
test("setup refuses a non-TTY before creating credential files", async () => {
|
||||
if (process.stdin.isTTY || process.stderr.isTTY) return;
|
||||
const directory = mkdtempSync(join(tmpdir(), "nocobase-mcp-nontty-"));
|
||||
const path = join(directory, "credentials.json");
|
||||
const previous = process.env.NOCOBASE_MCP_CREDENTIALS;
|
||||
process.env.NOCOBASE_MCP_CREDENTIALS = path;
|
||||
try {
|
||||
await assert.rejects(
|
||||
runCli(["setup", "--api-base-url", "https://nb.example", "--json"]),
|
||||
/local terminal/,
|
||||
);
|
||||
assert.equal(existsSync(path), false);
|
||||
assert.equal(existsSync(join(directory, "config.json")), false);
|
||||
} finally {
|
||||
if (previous === undefined) delete process.env.NOCOBASE_MCP_CREDENTIALS;
|
||||
else process.env.NOCOBASE_MCP_CREDENTIALS = previous;
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,169 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { mkdtempSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { afterEach, test } from "node:test";
|
||||
import { NocoBaseClient, NocoBaseError } from "../src/nocobase-client.js";
|
||||
|
||||
const originalFetch = globalThis.fetch;
|
||||
afterEach(() => {
|
||||
globalThis.fetch = originalFetch;
|
||||
});
|
||||
|
||||
function client(token = "personal-secret", dataSource = "main"): NocoBaseClient {
|
||||
return new NocoBaseClient(() => ({ apiBaseUrl: "https://nb.example/api", authorizeKey: token }), {
|
||||
dataSource,
|
||||
});
|
||||
}
|
||||
|
||||
test("sends list requests with the same HTTP contract as nb resource list", async () => {
|
||||
let request: Request | undefined;
|
||||
globalThis.fetch = async (input, init) => {
|
||||
request = new Request(input, init);
|
||||
return new Response(JSON.stringify({ data: [], meta: { count: 0 } }), {
|
||||
status: 200,
|
||||
headers: { "content-type": "application/json" },
|
||||
});
|
||||
};
|
||||
await client("key", "secondary").listRecords("customers", {
|
||||
filter: { status: { $eq: "active" } },
|
||||
fields: ["id", "name"],
|
||||
page: 2,
|
||||
pageSize: 20,
|
||||
});
|
||||
assert.ok(request);
|
||||
assert.equal(request.method, "POST");
|
||||
assert.equal(new URL(request.url).pathname, "/api/customers:list");
|
||||
assert.equal(
|
||||
new URL(request.url).searchParams.get("filter"),
|
||||
JSON.stringify({ status: { $eq: "active" } }),
|
||||
);
|
||||
assert.deepEqual(new URL(request.url).searchParams.getAll("fields"), ["id", "name"]);
|
||||
assert.equal(request.headers.get("authorization"), "Bearer key");
|
||||
assert.equal(request.headers.get("x-data-source"), "secondary");
|
||||
});
|
||||
|
||||
test("sends aggregation definitions in a JSON body with timezone header", async () => {
|
||||
let request: Request | undefined;
|
||||
globalThis.fetch = async (input, init) => {
|
||||
request = new Request(input, init);
|
||||
return new Response(JSON.stringify({ data: [{ count: 3 }] }), { status: 200 });
|
||||
};
|
||||
await client().queryRecords("customers", {
|
||||
measures: [{ field: ["id"], aggregation: "count", alias: "count" }],
|
||||
timezone: "Asia/Shanghai",
|
||||
});
|
||||
assert.ok(request);
|
||||
assert.equal(request.headers.get("x-timezone"), "Asia/Shanghai");
|
||||
assert.deepEqual(await request.json(), {
|
||||
measures: [{ field: ["id"], aggregation: "count", alias: "count" }],
|
||||
});
|
||||
});
|
||||
|
||||
test("reads credentials for every request", async () => {
|
||||
const seen: string[] = [];
|
||||
const keys = ["first", "second"];
|
||||
const rotating = new NocoBaseClient(() => ({
|
||||
apiBaseUrl: "https://nb.example/api",
|
||||
authorizeKey: keys.shift() ?? "missing",
|
||||
}));
|
||||
globalThis.fetch = async (input, init) => {
|
||||
seen.push(new Request(input, init).headers.get("authorization") ?? "");
|
||||
return new Response(JSON.stringify({ data: [] }), { status: 200 });
|
||||
};
|
||||
await rotating.listRecords("customers");
|
||||
await rotating.listRecords("customers");
|
||||
assert.deepEqual(seen, ["Bearer first", "Bearer second"]);
|
||||
});
|
||||
|
||||
test("redacts Authorize Keys and distinguishes expired auth from ACL denial", async () => {
|
||||
for (const [status, body, authenticationFailed] of [
|
||||
[401, "Bearer personal-secret INVALID_TOKEN", true],
|
||||
[403, "EXPIRED_TOKEN", true],
|
||||
[403, "NO_PERMISSIONS", false],
|
||||
] as const) {
|
||||
globalThis.fetch = async () => new Response(body, { status });
|
||||
await assert.rejects(client().listRecords("customers"), (error: unknown) => {
|
||||
assert.ok(error instanceof NocoBaseError);
|
||||
assert.equal(error.authenticationFailed, authenticationFailed);
|
||||
assert.doesNotMatch(error.message, /personal-secret/);
|
||||
return true;
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
test("rejects cross-origin redirects before forwarding authentication", async () => {
|
||||
globalThis.fetch = async () =>
|
||||
new Response(null, { status: 307, headers: { location: "https://evil.example/api" } });
|
||||
await assert.rejects(client().listRecords("customers"), /another origin/);
|
||||
});
|
||||
|
||||
test("builds data-model and attachment relation paths safely", async () => {
|
||||
const urls: string[] = [];
|
||||
globalThis.fetch = async (input) => {
|
||||
urls.push(String(input));
|
||||
return new Response(JSON.stringify({ data: [] }), { status: 200 });
|
||||
};
|
||||
await client()
|
||||
.listCollectionFields("crm customers")
|
||||
.then(
|
||||
() => assert.fail("invalid collection should fail"),
|
||||
() => undefined,
|
||||
);
|
||||
await client().listCollectionFields("crm_customers");
|
||||
await client().addAttachmentIds("../project/7?#", [8]);
|
||||
assert.match(urls[0] ?? "", /collections\/crm_customers\/fields:list/);
|
||||
assert.match(urls[1] ?? "", /t_projects\/..%2Fproject%2F7%3F%23\/f_projects_attachments:add/);
|
||||
await assert.rejects(client().addAttachmentIds("..", [8]), /dot path/);
|
||||
});
|
||||
|
||||
test("rejects nested project write values before sending a request", async () => {
|
||||
globalThis.fetch = async () => assert.fail("request must not be sent");
|
||||
await assert.rejects(client().createRecord("projects", { unsafe: { nested: true } }, ["unsafe"]), /scalar/);
|
||||
});
|
||||
|
||||
test("checks project ACL before attachment upload", async () => {
|
||||
const directory = mkdtempSync(join(tmpdir(), "nocobase-mcp-upload-"));
|
||||
const path = join(directory, "quote.pdf");
|
||||
writeFileSync(path, "pdf");
|
||||
const requests: Request[] = [];
|
||||
globalThis.fetch = async (input, init) => {
|
||||
const request = new Request(input, init);
|
||||
requests.push(request);
|
||||
if (new URL(request.url).pathname.endsWith("/roles:check")) {
|
||||
return new Response(
|
||||
JSON.stringify({ data: { strategy: { actions: ["view", "create"] }, resources: [] } }),
|
||||
{ status: 200 },
|
||||
);
|
||||
}
|
||||
return new Response(JSON.stringify({ data: { id: 42 } }), { status: 200 });
|
||||
};
|
||||
const uploaded = await client().uploadAttachment(path, "quote.pdf", "application/pdf");
|
||||
assert.equal(uploaded.id, 42);
|
||||
assert.equal(new URL(requests[0]?.url ?? "").pathname, "/api/roles:check");
|
||||
assert.equal(new URL(requests[1]?.url ?? "").pathname, "/api/attachments:create");
|
||||
assert.equal(
|
||||
new URL(requests[1]?.url ?? "").searchParams.get("attachmentField"),
|
||||
"t_projects.f_projects_attachments",
|
||||
);
|
||||
});
|
||||
|
||||
test("denies attachment upload before create when project ACL is missing", async () => {
|
||||
const directory = mkdtempSync(join(tmpdir(), "nocobase-mcp-upload-denied-"));
|
||||
const path = join(directory, "quote.pdf");
|
||||
writeFileSync(path, "pdf");
|
||||
let requests = 0;
|
||||
globalThis.fetch = async () => {
|
||||
requests += 1;
|
||||
return new Response(
|
||||
JSON.stringify({ data: { strategy: { actions: ["view:own", "trigger:own"] }, resources: [] } }),
|
||||
{ status: 200 },
|
||||
);
|
||||
};
|
||||
await assert.rejects(client().uploadAttachment(path), (error: unknown) => {
|
||||
assert.ok(error instanceof NocoBaseError);
|
||||
assert.equal(error.statusCode, 403);
|
||||
return true;
|
||||
});
|
||||
assert.equal(requests, 1);
|
||||
});
|
||||
@@ -0,0 +1,56 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { chmodSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import test from "node:test";
|
||||
import { DEFAULT_CONFIG, loadConfig } from "../src/config.js";
|
||||
import { loadCredentials, normalizeApiBaseUrl, saveCredentials } from "../src/credentials.js";
|
||||
|
||||
test("normalizes application URLs to the NocoBase API base", () => {
|
||||
assert.equal(normalizeApiBaseUrl("https://nb.example/app/"), "https://nb.example/app/api");
|
||||
assert.equal(normalizeApiBaseUrl("http://127.0.0.1:13000/api"), "http://127.0.0.1:13000/api");
|
||||
assert.throws(() => normalizeApiBaseUrl("http://nb.example"), /HTTPS/i);
|
||||
assert.throws(() => normalizeApiBaseUrl("https://user:pass@nb.example"), /credentials/i);
|
||||
});
|
||||
|
||||
test("stores and reads credentials from a private file", () => {
|
||||
const directory = mkdtempSync(join(tmpdir(), "nocobase-mcp-credentials-"));
|
||||
const path = join(directory, "private", "credentials.json");
|
||||
saveCredentials({ apiBaseUrl: "https://nb.example", authorizeKey: "secret" }, path);
|
||||
assert.deepEqual(loadCredentials(path), {
|
||||
apiBaseUrl: "https://nb.example/api",
|
||||
authorizeKey: "secret",
|
||||
});
|
||||
assert.match(readFileSync(path, "utf8"), /secret/);
|
||||
if (process.platform !== "win32") {
|
||||
chmodSync(path, 0o644);
|
||||
assert.throws(() => loadCredentials(path), /0600/);
|
||||
}
|
||||
});
|
||||
|
||||
test("loads camelCase and snake_case config aliases without mutating defaults", () => {
|
||||
const directory = mkdtempSync(join(tmpdir(), "nocobase-mcp-config-"));
|
||||
const path = join(directory, "config.json");
|
||||
writeFileSync(
|
||||
path,
|
||||
JSON.stringify({
|
||||
data_source: "secondary",
|
||||
timezone: "UTC",
|
||||
collections: { customers: { resource: "crm_customers", owner_field: "assignee" } },
|
||||
projects: { nameField: "project_title" },
|
||||
}),
|
||||
);
|
||||
const loaded = loadConfig(path);
|
||||
assert.equal(loaded.dataSource, "secondary");
|
||||
assert.equal(loaded.customer.resource, "crm_customers");
|
||||
assert.equal(loaded.customer.ownerField, "assignee");
|
||||
assert.equal(loaded.project.nameField, "project_title");
|
||||
assert.equal(DEFAULT_CONFIG.customer.resource, "customers");
|
||||
});
|
||||
|
||||
test("rejects malformed config types before any NocoBase request", () => {
|
||||
const directory = mkdtempSync(join(tmpdir(), "nocobase-mcp-invalid-config-"));
|
||||
const path = join(directory, "config.json");
|
||||
writeFileSync(path, JSON.stringify({ collections: { customers: { fields: "id,name" } } }));
|
||||
assert.throws(() => loadConfig(path), /array of strings/);
|
||||
});
|
||||
@@ -0,0 +1,193 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { DEFAULT_CONFIG } from "../src/config.js";
|
||||
import { CrmService } from "../src/crm-service.js";
|
||||
import type { NocoBaseClient } from "../src/nocobase-client.js";
|
||||
|
||||
test("renders compact customer rows, labels, relations, timezone, and pagination", async () => {
|
||||
const requests: Array<Record<string, unknown>> = [];
|
||||
const fake = {
|
||||
listRecords: async (resource: string, options: Record<string, unknown>) => {
|
||||
requests.push({ resource, ...options });
|
||||
return {
|
||||
data: [
|
||||
{
|
||||
id: 42,
|
||||
f_q2q60q7bqbg: "Acme",
|
||||
kh_progress: "kh_p_inprogress",
|
||||
f_225h6n6v654: "Referral",
|
||||
kehu_followup_person: [{ id: 7, nickname: "Alice" }],
|
||||
updatedAt: "2026-07-08T09:00:00Z",
|
||||
},
|
||||
],
|
||||
meta: { count: 1 },
|
||||
};
|
||||
},
|
||||
} as unknown as NocoBaseClient;
|
||||
const config = structuredClone(DEFAULT_CONFIG);
|
||||
config.customer.resource = "crm_customers";
|
||||
config.customer.fields = [
|
||||
"id",
|
||||
"f_q2q60q7bqbg",
|
||||
"kh_progress",
|
||||
"f_225h6n6v654",
|
||||
"kehu_followup_person",
|
||||
"updatedAt",
|
||||
];
|
||||
config.customer.statusField = "kh_progress";
|
||||
config.customer.sourceField = "f_225h6n6v654";
|
||||
config.customer.ownerField = "kehu_followup_person";
|
||||
const result = await new CrmService(config, fake).listCustomers({ limit: 20 });
|
||||
assert.deepEqual(result.results, [
|
||||
{
|
||||
id: 42,
|
||||
name: "Acme",
|
||||
status: "进行中",
|
||||
source: "Referral",
|
||||
owners: [{ id: 7, name: "Alice" }],
|
||||
updatedAt: "2026-07-08T17:00:00+08:00",
|
||||
},
|
||||
]);
|
||||
assert.equal(result.total, 1);
|
||||
assert.equal(result.timezone, "Asia/Shanghai");
|
||||
assert.equal(requests[0]?.resource, "crm_customers");
|
||||
});
|
||||
|
||||
test("implements exact arbitrary offsets across two NocoBase pages", async () => {
|
||||
const pages: number[] = [];
|
||||
const fake = {
|
||||
listRecords: async (_resource: string, options: Record<string, unknown>) => {
|
||||
const page = options.page as number;
|
||||
pages.push(page);
|
||||
const start = (page - 1) * 20;
|
||||
return {
|
||||
data: Array.from({ length: 20 }, (_, index) => ({
|
||||
id: start + index,
|
||||
name: `Customer ${start + index}`,
|
||||
})),
|
||||
meta: { count: 100 },
|
||||
};
|
||||
},
|
||||
} as unknown as NocoBaseClient;
|
||||
const result = await new CrmService(structuredClone(DEFAULT_CONFIG), fake).listCustomers({
|
||||
limit: 20,
|
||||
offset: 25,
|
||||
});
|
||||
assert.deepEqual(pages, [2, 3]);
|
||||
assert.deepEqual(
|
||||
(result.results as Array<Record<string, unknown>>).map((row) => row.id),
|
||||
Array.from({ length: 20 }, (_, i) => 25 + i),
|
||||
);
|
||||
assert.equal(result.next_offset, 45);
|
||||
});
|
||||
|
||||
test("resolves owner candidates and returns ambiguity as structured data", async () => {
|
||||
const fake = {
|
||||
listRecords: async (resource: string) => {
|
||||
if (resource === "users") {
|
||||
return {
|
||||
data: [
|
||||
{ id: 1, username: "alex", nickname: "Alex A" },
|
||||
{ id: 2, username: "alex", nickname: "Alex B" },
|
||||
],
|
||||
};
|
||||
}
|
||||
return { data: [], meta: { count: 0 } };
|
||||
},
|
||||
} as unknown as NocoBaseClient;
|
||||
const service = new CrmService(structuredClone(DEFAULT_CONFIG), fake);
|
||||
const resolved = await service.resolveOwner("alex");
|
||||
assert.equal(resolved.count, 2);
|
||||
const listed = await service.listCustomers({ owner: "alex" });
|
||||
assert.equal((listed.error as Record<string, unknown>).code, "owner_ambiguous");
|
||||
});
|
||||
|
||||
test("health never returns the Authorize Key", async () => {
|
||||
const fake = {
|
||||
health: async () => ({ ok: true, endpoint: "https://nb.example", status: "authenticated" }),
|
||||
} as unknown as NocoBaseClient;
|
||||
const result = await new CrmService(structuredClone(DEFAULT_CONFIG), fake).crmHealth();
|
||||
assert.equal(result.ok, true);
|
||||
assert.doesNotMatch(JSON.stringify(result), /token|secret|authorizeKey/i);
|
||||
});
|
||||
|
||||
test("all CRM service surfaces execute against the direct HTTP adapter contract", async () => {
|
||||
const config = structuredClone(DEFAULT_CONFIG);
|
||||
const rows: Record<string, Record<string, unknown>> = {
|
||||
[config.customer.resource]: {
|
||||
id: 1,
|
||||
name: "Acme",
|
||||
owner: [{ id: 10, nickname: "Alice" }],
|
||||
updatedAt: "2026-01-01T00:00:00Z",
|
||||
},
|
||||
[config.contact.resource]: { id: 2, name: "Bob", customer: [{ id: 1, name: "Acme" }] },
|
||||
[config.followup.resource]: {
|
||||
id: 3,
|
||||
followedAt: "2026-01-02T00:00:00Z",
|
||||
customer: [{ id: 1, name: "Acme" }],
|
||||
owner: [{ id: 10, nickname: "Alice" }],
|
||||
content: "Followed up",
|
||||
},
|
||||
[config.user.resource]: {
|
||||
id: 10,
|
||||
username: "alice",
|
||||
nickname: "Alice",
|
||||
[config.team.userStatusField]: config.team.formalUserStatusValue,
|
||||
},
|
||||
[config.team.resource]: {
|
||||
id: 20,
|
||||
[config.team.nameField]: "Alpha",
|
||||
[config.team.managerField]: [{ id: 10 }],
|
||||
[config.team.memberField]: [{ id: 10 }],
|
||||
},
|
||||
[config.project.resource]: {
|
||||
id: 30,
|
||||
[config.project.nameField]: "Project",
|
||||
[config.project.progressField]: config.project.progressValues.已报价,
|
||||
[config.project.customerRelationField]: [{ id: 1, name: "Acme" }],
|
||||
},
|
||||
[config.project.updateResource]: {
|
||||
id: 31,
|
||||
[config.project.updateDateField]: "2026-01-03T00:00:00Z",
|
||||
[config.project.updateContentField]: "Updated",
|
||||
createdBy: [{ id: 10, nickname: "Alice" }],
|
||||
},
|
||||
};
|
||||
const fake = {
|
||||
health: async () => ({ ok: true, endpoint: "https://nb.example", status: "authenticated" }),
|
||||
listCollectionFields: async () => ({ data: [] }),
|
||||
getRecord: async (resource: string) => ({ data: rows[resource] }),
|
||||
listRecords: async (resource: string) => ({
|
||||
data: rows[resource] ? [rows[resource]] : [],
|
||||
meta: { count: rows[resource] ? 1 : 0 },
|
||||
}),
|
||||
queryRecords: async (_resource: string, options: Record<string, unknown>) => {
|
||||
const dimensions = options.dimensions as Array<Record<string, unknown>> | undefined;
|
||||
const alias = dimensions?.[0]?.alias;
|
||||
return { data: [{ ...(typeof alias === "string" ? { [alias]: "value" } : {}), count: 1 }] };
|
||||
},
|
||||
} as unknown as NocoBaseClient;
|
||||
const service = new CrmService(config, fake);
|
||||
const results = await Promise.all([
|
||||
service.crmHealth(),
|
||||
service.crmSchema(true),
|
||||
service.crmConfigTemplate(),
|
||||
service.listCustomers(),
|
||||
service.getCustomer(1),
|
||||
service.listContacts(),
|
||||
service.listFollowups(),
|
||||
service.listProjects(),
|
||||
service.getProject(30),
|
||||
service.resolveOwner("alice"),
|
||||
service.listTeams({ includeMembers: true }),
|
||||
service.resolveTeam("Alpha"),
|
||||
service.getTeam(20),
|
||||
service.crmOverview(),
|
||||
service.crmFilterOptions("alice"),
|
||||
service.teamCrmOverview("Alpha"),
|
||||
service.getProjectTimeline(30),
|
||||
service.listStaleCustomers({ asOf: "2026-08-15", inactiveDays: 30 }),
|
||||
]);
|
||||
assert.equal(results.length, 18);
|
||||
assert.ok(results.every((result) => !("error" in result)));
|
||||
});
|
||||
@@ -0,0 +1,61 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import {
|
||||
fieldsWithProjections,
|
||||
normalizePagination,
|
||||
prune,
|
||||
relationRefs,
|
||||
toZonedIso,
|
||||
} from "../src/crm-helpers.js";
|
||||
import {
|
||||
buildAndFilter,
|
||||
buildDateRangeCondition,
|
||||
buildRelationIdCondition,
|
||||
buildRelationIdInCondition,
|
||||
buildSearchFilter,
|
||||
} from "../src/filters.js";
|
||||
|
||||
test("builds nested NocoBase filters", () => {
|
||||
assert.deepEqual(buildRelationIdCondition("owner", 7), { owner: { id: { $eq: 7 } } });
|
||||
assert.deepEqual(buildRelationIdCondition(["customer", "owner", "id"], 9), {
|
||||
customer: { owner: { id: { $eq: 9 } } },
|
||||
});
|
||||
assert.deepEqual(buildRelationIdInCondition("owner", [1, 2]), { owner: { id: { $in: [1, 2] } } });
|
||||
assert.deepEqual(buildDateRangeCondition("createdAt", "2026-01-01", "2026-01-31"), {
|
||||
createdAt: { $dateBetween: ["2026-01-01", "2026-01-31"] },
|
||||
});
|
||||
assert.deepEqual(buildSearchFilter("Acme", ["name", "code"]), {
|
||||
$or: [{ name: { $includes: "Acme" } }, { code: { $includes: "Acme" } }],
|
||||
});
|
||||
assert.deepEqual(buildAndFilter([undefined]), {});
|
||||
});
|
||||
|
||||
test("normalizes pagination and relation projections", () => {
|
||||
assert.deepEqual(normalizePagination(500, -3), [100, 0]);
|
||||
assert.deepEqual(fieldsWithProjections(["id", "owner"], ["owner.id", "owner.nickname"]), [
|
||||
"id",
|
||||
"owner.id",
|
||||
"owner.nickname",
|
||||
]);
|
||||
});
|
||||
|
||||
test("renders relation references without treating an id as a real name", () => {
|
||||
const refs = relationRefs(
|
||||
{ customers: [{ id: 42 }, { id: 43, title: "Acme" }, { id: 43, title: "duplicate" }] },
|
||||
["customers"],
|
||||
{ idField: "id", nameFields: ["title"] },
|
||||
);
|
||||
assert.deepEqual(refs, [
|
||||
{ id: 42, name: "#42" },
|
||||
{ id: 43, name: "Acme" },
|
||||
]);
|
||||
assert.deepEqual(prune({ id: 1, name: "", rows: [], value: null, active: false }), {
|
||||
id: 1,
|
||||
active: false,
|
||||
});
|
||||
});
|
||||
|
||||
test("formats timestamps in the configured timezone while preserving dates", () => {
|
||||
assert.equal(toZonedIso("2026-07-08T09:00:00Z", "Asia/Shanghai"), "2026-07-08T17:00:00+08:00");
|
||||
assert.equal(toZonedIso("2026-07-08", "Asia/Shanghai"), "2026-07-08");
|
||||
});
|
||||
@@ -0,0 +1,58 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { DEFAULT_CONFIG } from "../src/config.js";
|
||||
import type { NocoBaseClient } from "../src/nocobase-client.js";
|
||||
import { ProjectService } from "../src/project-service.js";
|
||||
|
||||
test("creates fixed-schema projects and translates progress labels", async () => {
|
||||
const calls: unknown[][] = [];
|
||||
const fake = {
|
||||
createRecord: async (...args: unknown[]) => {
|
||||
calls.push(args);
|
||||
return { data: { id: 42 } };
|
||||
},
|
||||
addAttachmentIds: async (...args: unknown[]) => calls.push(args),
|
||||
} as unknown as NocoBaseClient;
|
||||
const service = new ProjectService(DEFAULT_CONFIG.project, fake);
|
||||
assert.deepEqual(
|
||||
await service.createProject({
|
||||
name: " EV inverter ",
|
||||
progress: "已报价",
|
||||
customerId: 7,
|
||||
attachmentIds: [8, 8, 9],
|
||||
}),
|
||||
{ project_id: 42 },
|
||||
);
|
||||
assert.ok(calls[0]);
|
||||
assert.deepEqual(
|
||||
(calls[0][1] as Record<string, unknown>)[DEFAULT_CONFIG.project.progressField],
|
||||
"k4w2vcz819w",
|
||||
);
|
||||
assert.deepEqual(calls[1], [42, [8, 9]]);
|
||||
});
|
||||
|
||||
test("validates project inputs before writes", async () => {
|
||||
const fake = {
|
||||
createRecord: async () => assert.fail("must not write"),
|
||||
updateRecord: async () => assert.fail("must not write"),
|
||||
} as unknown as NocoBaseClient;
|
||||
const service = new ProjectService(DEFAULT_CONFIG.project, fake);
|
||||
assert.equal(
|
||||
((await service.createProject({ name: " " })).error as Record<string, unknown>).code,
|
||||
"invalid_project_input",
|
||||
);
|
||||
assert.equal(
|
||||
((await service.createProject({ name: "Project", progress: "unknown" })).error as Record<string, unknown>)
|
||||
.code,
|
||||
"invalid_progress",
|
||||
);
|
||||
assert.equal(
|
||||
(
|
||||
(await service.updateProject(1, { addAttachmentIds: [8], removeAttachmentIds: [8] })).error as Record<
|
||||
string,
|
||||
unknown
|
||||
>
|
||||
).code,
|
||||
"invalid_project_input",
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,97 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
|
||||
import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js";
|
||||
import type { CrmService } from "../src/crm-service.js";
|
||||
import type { ProjectService } from "../src/project-service.js";
|
||||
import { createServer } from "../src/tools.js";
|
||||
|
||||
function fakeService(): CrmService {
|
||||
return new Proxy(
|
||||
{},
|
||||
{
|
||||
get:
|
||||
(_target, property) =>
|
||||
async (...args: unknown[]) => ({ operation: String(property), args }),
|
||||
},
|
||||
) as CrmService;
|
||||
}
|
||||
|
||||
async function connected(readonly: boolean): Promise<{
|
||||
client: Client;
|
||||
close: () => Promise<void>;
|
||||
}> {
|
||||
const server = createServer({
|
||||
crmService: fakeService(),
|
||||
projectService: fakeService() as unknown as ProjectService,
|
||||
readonly,
|
||||
});
|
||||
const client = new Client({ name: "test", version: "1" });
|
||||
const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
|
||||
await Promise.all([server.connect(serverTransport), client.connect(clientTransport)]);
|
||||
return {
|
||||
client,
|
||||
close: async () => await Promise.all([client.close(), server.close()]).then(() => undefined),
|
||||
};
|
||||
}
|
||||
|
||||
test("read-only server exposes the stable 17-tool contract", async () => {
|
||||
const connection = await connected(true);
|
||||
try {
|
||||
const result = await connection.client.listTools();
|
||||
assert.deepEqual(
|
||||
new Set(result.tools.map((tool) => tool.name)),
|
||||
new Set([
|
||||
"crm_health",
|
||||
"crm_schema",
|
||||
"crm_overview",
|
||||
"crm_filter_options",
|
||||
"resolve_owner",
|
||||
"list_teams",
|
||||
"resolve_team",
|
||||
"get_team",
|
||||
"team_crm_overview",
|
||||
"list_customers",
|
||||
"get_customer",
|
||||
"list_contacts",
|
||||
"list_followups",
|
||||
"list_projects",
|
||||
"get_project",
|
||||
"get_project_timeline",
|
||||
"list_stale_customers",
|
||||
]),
|
||||
);
|
||||
} finally {
|
||||
await connection.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("write mode adds only fixed project create and update tools", async () => {
|
||||
const connection = await connected(false);
|
||||
try {
|
||||
const names = (await connection.client.listTools()).tools.map((tool) => tool.name);
|
||||
assert.ok(names.includes("create_project"));
|
||||
assert.ok(names.includes("update_project"));
|
||||
assert.ok(!names.some((name) => name.includes("destroy") || name.includes("delete")));
|
||||
} finally {
|
||||
await connection.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("raw rows require explicit local policy opt-in", async () => {
|
||||
const previous = process.env.NOCOBASE_MCP_ENABLE_RAW_DATA;
|
||||
delete process.env.NOCOBASE_MCP_ENABLE_RAW_DATA;
|
||||
const connection = await connected(true);
|
||||
try {
|
||||
const result = await connection.client.callTool({
|
||||
name: "list_customers",
|
||||
arguments: { include_raw: true },
|
||||
});
|
||||
const structured = result.structuredContent as { error: Record<string, unknown> };
|
||||
assert.equal(structured.error.code, "raw_data_disabled");
|
||||
} finally {
|
||||
if (previous === undefined) delete process.env.NOCOBASE_MCP_ENABLE_RAW_DATA;
|
||||
else process.env.NOCOBASE_MCP_ENABLE_RAW_DATA = previous;
|
||||
await connection.close();
|
||||
}
|
||||
});
|
||||
Reference in New Issue
Block a user