@centrali-io/centrali-mcp 9.5.1 → 9.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,143 @@
1
+ const test = require("node:test");
2
+ const assert = require("node:assert/strict");
3
+ const http = require("node:http");
4
+ const { CentraliSDK } = require("@centrali-io/centrali-sdk");
5
+ const { registerFileTools } = require("../dist/tools/files.js");
6
+
7
+ const base = { filename: "image.png", contentType: "image/png", contentEncoding: "base64", content: "AAEC/w==" };
8
+
9
+ function setup(sdk) {
10
+ let handler;
11
+ registerFileTools({ tool: (_name, _description, _schema, fn) => { handler = fn; } }, sdk);
12
+ return handler;
13
+ }
14
+
15
+ test("uploads exact binary bytes privately and returns file handles without content", async () => {
16
+ let uploaded;
17
+ const handler = setup({
18
+ uploadFile: async (file, location, isPublic) => {
19
+ uploaded = { file, location, isPublic };
20
+ return { data: "render-id" };
21
+ },
22
+ getFileRenderUrl: id => `https://example.test/render/${id}`,
23
+ getFileDownloadUrl: id => `https://example.test/download/${id}`,
24
+ });
25
+ const result = await handler(base);
26
+ assert.equal(result.isError, undefined);
27
+ assert.deepEqual(Buffer.from(await uploaded.file.arrayBuffer()), Buffer.from([0, 1, 2, 255]));
28
+ assert.equal(uploaded.file.name, "image.png");
29
+ assert.equal(uploaded.file.type, "image/png");
30
+ assert.equal(uploaded.location, undefined);
31
+ assert.equal(uploaded.isPublic, false);
32
+ assert.deepEqual(JSON.parse(result.content[0].text), {
33
+ renderId: "render-id", sizeBytes: 4, contentType: "image/png", isPublic: false,
34
+ renderUrl: "https://example.test/render/render-id", downloadUrl: "https://example.test/download/render-id",
35
+ });
36
+ });
37
+
38
+ test("rejects malformed, noncanonical and oversized content before calling Storage", async () => {
39
+ const handler = setup({ uploadFile: async () => { assert.fail("must not upload invalid input"); } });
40
+ for (const changes of [
41
+ { content: "%%%!" }, { content: "Zg" }, { content: "Zh==" },
42
+ { content: "data:image/png;base64,AAEC/w==" }, { content: "AAEC/w==\n" },
43
+ { filename: "../image.png" }, { filename: "a\\b" },
44
+ { contentType: "image/png\r\nX-Test: x" }, { contentEncoding: "hex" },
45
+ { content: Buffer.alloc(256 * 1024 + 1).toString("base64") },
46
+ { contentEncoding: "utf8", content: "é".repeat(128 * 1024 + 1) },
47
+ ]) {
48
+ const result = await handler({ ...base, ...changes });
49
+ assert.equal(result.isError, true, JSON.stringify(Object.keys(changes)));
50
+ assert.ok(result.content[0].text.length < 300, "errors must not echo file bytes");
51
+ }
52
+ });
53
+
54
+ test("public uploads reject active and unlisted MIME types before reaching Storage", async () => {
55
+ const handler = setup({ uploadFile: async () => { assert.fail("must not upload public active content"); } });
56
+ for (const contentType of ["text/html", "TEXT/HTML", "image/svg+xml", "application/xhtml+xml", "application/xml", "application/pdf", "application/octet-stream"]) {
57
+ const result = await handler({ ...base, contentType, isPublic: true });
58
+ assert.equal(result.isError, true, contentType);
59
+ assert.match(result.content[0].text, /passive MIME type/);
60
+ }
61
+ });
62
+
63
+ test("private active documents and empty files preserve their exact content", async () => {
64
+ const calls = [];
65
+ const handler = setup({
66
+ uploadFile: async (file, _location, isPublic) => {
67
+ calls.push({ bytes: Buffer.from(await file.arrayBuffer()), isPublic, type: file.type });
68
+ return { data: "id" };
69
+ },
70
+ getFileRenderUrl: () => "render", getFileDownloadUrl: () => "download",
71
+ });
72
+ for (const contentEncoding of ["base64", "utf8"]) {
73
+ const result = await handler({ ...base, contentEncoding, content: "" });
74
+ assert.equal(result.isError, undefined);
75
+ assert.equal(JSON.parse(result.content[0].text).sizeBytes, 0);
76
+ }
77
+ assert.equal((await handler({ ...base, contentType: "text/html", contentEncoding: "utf8", content: "<p>hello</p>" })).isError, undefined);
78
+ assert.deepEqual(calls.map(call => call.isPublic), [false, false, false]);
79
+ assert.equal(calls[2].bytes.toString(), "<p>hello</p>");
80
+ });
81
+
82
+ test("JSON escaping is bounded while base64 still supports 256 KiB of control bytes", async () => {
83
+ let calls = 0;
84
+ const handler = setup({
85
+ uploadFile: async () => { calls++; return { data: "id" }; },
86
+ getFileRenderUrl: () => "render", getFileDownloadUrl: () => "download",
87
+ });
88
+ const content = "\u0000".repeat(256 * 1024);
89
+ assert.equal((await handler({ ...base, contentEncoding: "utf8", content })).isError, true);
90
+ assert.equal(calls, 0);
91
+ const accepted = { ...base, contentEncoding: "utf8", content: "\u0000".repeat(120 * 1024) };
92
+ assert.ok(Buffer.byteLength(JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "upload_file", arguments: accepted } })) < 1024 * 1024);
93
+ assert.equal((await handler(accepted)).isError, undefined);
94
+ assert.equal((await handler({ ...base, content: Buffer.from(content).toString("base64") })).isError, undefined);
95
+ assert.equal(calls, 2);
96
+ });
97
+
98
+ test("accepts the exact decoded size limit", async () => {
99
+ const handler = setup({
100
+ uploadFile: async file => { assert.equal(file.size, 256 * 1024); return { data: "id" }; },
101
+ getFileRenderUrl: () => "render", getFileDownloadUrl: () => "download",
102
+ });
103
+ assert.equal((await handler({ ...base, content: Buffer.alloc(256 * 1024).toString("base64") })).isError, undefined);
104
+ });
105
+
106
+ test("reports Storage authorization and folder failures as tool errors", async () => {
107
+ for (const status of [403, 404, 409, 500]) {
108
+ const handler = setup({ uploadFile: async () => { throw { status, message: "Upload refused" }; } });
109
+ const result = await handler(base);
110
+ assert.equal(result.isError, true);
111
+ assert.match(result.content[0].text, new RegExp(String(status)));
112
+ }
113
+ });
114
+
115
+ test("real SDK sends authenticated workspace multipart, UTF-8, folder and explicit visibility", async t => {
116
+ let captured;
117
+ const server = http.createServer(async (req, res) => {
118
+ const chunks = [];
119
+ for await (const chunk of req) chunks.push(chunk);
120
+ captured = { url: req.url, headers: req.headers, body: Buffer.concat(chunks).toString("utf8") };
121
+ res.setHeader("Content-Type", "application/json");
122
+ res.end(JSON.stringify("render-id"));
123
+ });
124
+ await new Promise(resolve => server.listen(0, "127.0.0.1", resolve));
125
+ t.after(() => new Promise(resolve => server.close(resolve)));
126
+ const baseUrl = `http://127.0.0.1:${server.address().port}`;
127
+ const sdk = new CentraliSDK({ baseUrl, workspaceId: "authenticated-workspace", axiosConfig: { baseURL: baseUrl } });
128
+ sdk.setToken("test-token");
129
+ const result = await setup(sdk)({
130
+ ...base, filename: "note.txt", contentType: "text/plain", contentEncoding: "utf8",
131
+ content: "Hello 🌍", location: "/root/shared/notes", isPublic: true,
132
+ workspaceId: "attacker-workspace",
133
+ });
134
+ assert.equal(result.isError, undefined, result.content[0].text);
135
+ assert.match(captured.url, /authenticated-workspace/);
136
+ assert.ok(!captured.url.includes("attacker-workspace"));
137
+ assert.equal(captured.headers.authorization, "Bearer test-token");
138
+ assert.match(captured.headers["content-type"], /multipart\/form-data; boundary=/);
139
+ assert.match(captured.body, /filename="note.txt"/);
140
+ assert.match(captured.body, /Hello 🌍/);
141
+ assert.match(captured.body, /name="location"\r\n\r\n\/root\/shared\/notes/);
142
+ assert.match(captured.body, /name="isPublic"\r\n\r\ntrue/);
143
+ });
@@ -0,0 +1,94 @@
1
+ const test = require('node:test');
2
+ const assert = require('node:assert/strict');
3
+ const axios = require('axios');
4
+ const { registerServiceAccountTools } = require('../dist/tools/service-accounts.js');
5
+
6
+ const paths = [
7
+ ['get_service_account', 'get', ''],
8
+ ['update_service_account_name', 'put', '/name'],
9
+ ['update_service_account_description', 'put', '/description'],
10
+ ['delete_service_account', 'delete', ''],
11
+ ['rotate_service_account_secret', 'post', '/rotate'],
12
+ ['revoke_service_account', 'post', '/revoke'],
13
+ ['generate_dev_token', 'post', '/dev-token'],
14
+ ['scan_service_account_permissions', 'get', '/permissions/scan'],
15
+ ['simulate_service_account_permission', 'post', '/permissions/simulate'],
16
+ ['list_service_account_roles', 'get', '/roles'],
17
+ ['assign_role_to_service_account', 'post', '/roles/role-1'],
18
+ ['remove_role_from_service_account', 'delete', '/roles/role-1'],
19
+ ['list_service_account_groups', 'get', '/groups'],
20
+ ['add_service_account_to_group', 'post', '/groups/group-1'],
21
+ ['remove_service_account_from_group', 'delete', '/groups/group-1'],
22
+ ];
23
+ // Capture actual Axios requests without contacting IAM.
24
+ function setup(accounts = []) {
25
+ const calls = [];
26
+ const tools = new Map();
27
+ const create = axios.create;
28
+ axios.create = () => {
29
+ const client = { interceptors: { request: { use() {} }, response: { use() {} } } };
30
+ for (const method of ['get', 'post', 'put', 'delete']) {
31
+ client[method] = async (path, body) => { calls.push({ method, path, body }); return { data: method === 'get' && path === '/' ? { data: accounts } : {} }; };
32
+ }
33
+ return client;
34
+ };
35
+ registerServiceAccountTools({ tool(name, desc, schema, handler) { tools.set(name, { description: desc, schema, handler }); } }, {}, 'https://api.example.com', 'acme', { clientId: 'sa_identity' });
36
+ return { calls, tools, restore: () => { axios.create = create; } };
37
+ }
38
+ for (const [name, method, suffix] of paths) {
39
+ test(`${name}: string clientId contract and account path`, async () => {
40
+ const { calls, tools, restore } = setup();
41
+ try {
42
+ const tool = tools.get(name);
43
+ assert.ok(tool, name);
44
+ assert.equal(tool.schema.clientId.safeParse('cid_legacy').success, true);
45
+ assert.equal(tool.schema.clientId.safeParse(2403).success, false);
46
+ assert.equal(tool.schema.serviceAccountId, undefined);
47
+ const result = await tool.handler({ clientId: 'cid_legacy', roleId: 'role-1', groupId: 'group-1', name: 'Changed', description: 'Changed', ttlSeconds: 3600, resource: 'records', resourceCategory: 'workspace', action: 'retrieve' });
48
+ assert.ok(!result.isError);
49
+ assert.equal(calls[0].method, method);
50
+ assert.equal(calls[0].path, `/cid_legacy${suffix}`);
51
+ } finally { restore(); }
52
+ });
53
+ }
54
+ test('remediation retains its explicit numeric targetId contract', async () => {
55
+ const { calls, tools, restore } = setup();
56
+ try {
57
+ const tool = tools.get('generate_remediation');
58
+ assert.equal(tool.schema.serviceAccountId.safeParse(2403).success, true);
59
+ await tool.handler({ serviceAccountId: 2403, resource: 'records', resourceCategory: 'workspace', actions: ['retrieve'] });
60
+ assert.equal(calls[0].body.targetId, 2403);
61
+ } finally { restore(); }
62
+ });
63
+
64
+ // Agent-facing instructions are part of the tool contract, alongside schemas.
65
+ test('identity guidance separates clientId inspection from numeric remediation', async () => {
66
+ const { tools, restore } = setup([{ id: 2403, clientId: 'sa_identity', name: 'Identity' }]);
67
+ try {
68
+ const result = await tools.get('get_current_identity').handler({});
69
+ assert.ok(!result.isError);
70
+ const identity = JSON.parse(result.content[0].text);
71
+ assert.equal(identity.id, 2403);
72
+ assert.equal(identity.clientId, 'sa_identity');
73
+ const [inspection, remediation] = identity._hint.split('. ');
74
+ assert.match(inspection, /clientId.*scan_service_account_permissions.*simulate_service_account_permission/);
75
+ assert.doesNotMatch(inspection, /numeric/);
76
+ assert.match(remediation, /numeric id as serviceAccountId.*generate_remediation.*preview_remediation.*apply_remediation/);
77
+ } finally { restore(); }
78
+ });
79
+ test('get description advertises the clientId argument', () => {
80
+ const { tools, restore } = setup();
81
+ try {
82
+ const description = tools.get('get_service_account').description;
83
+ assert.match(description, /by its clientId/);
84
+ assert.doesNotMatch(description, /by its numeric ID/);
85
+ } finally { restore(); }
86
+ });
87
+ test('delete description permits already-revoked accounts', () => {
88
+ const { tools, restore } = setup();
89
+ try {
90
+ const description = tools.get('delete_service_account').description;
91
+ assert.match(description, /including an already-revoked account/);
92
+ assert.doesNotMatch(description, /must not be revoked|revoke prevents deletion/);
93
+ } finally { restore(); }
94
+ });
@@ -0,0 +1,37 @@
1
+ const test = require('node:test');
2
+ const assert = require('node:assert/strict');
3
+ const { registerInsightTools } = require('../dist/tools/insights.js');
4
+
5
+ test('trigger health tool exposes independent metrics and routes workspace / trigger reads', async () => {
6
+ const tools = new Map();
7
+ const calls = [];
8
+ const metrics = { receivedCount: 12, rejectedCount: 12, requestAcceptanceRate: 0, executionSuccessRate: 1 };
9
+ registerInsightTools({ tool: (name, description, schema, handler) => tools.set(name, { description, schema, handler }) }, {
10
+ triggers: {
11
+ health: async (...args) => { calls.push(['list', ...args]); return { data: metrics }; },
12
+ healthTrend: async (...args) => { calls.push(['trend', ...args]); return { data: metrics }; },
13
+ },
14
+ });
15
+ const tool = tools.get('get_trigger_health');
16
+ assert.match(tool.description, /executionSuccessRate/);
17
+ assert.equal(tool.schema.period.safeParse(14).success, false);
18
+ assert.equal(tool.schema.triggerId.safeParse('bad-id').success, false);
19
+ assert.deepEqual(JSON.parse((await tool.handler({ period: 7 })).content[0].text), metrics);
20
+ await tool.handler({ triggerId: 'trigger-1', period: 30 });
21
+ assert.deepEqual(calls, [['list', 7], ['trend', 'trigger-1', 30]]);
22
+ });
23
+
24
+ test('real SDK controller envelopes keep workspace metadata and trend summary in MCP output', async () => {
25
+ const { CentraliSDK } = require('@centrali-io/centrali-sdk');
26
+ const tools = new Map();
27
+ const summary = { executionSuccessRate: 1, requestAcceptanceRate: 0, rejectedCount: 12 };
28
+ const list = { data: [{ triggerId: 't', ...summary }], meta: { unattributedRequests: { rejectedCount: 3 } } };
29
+ const trend = { trigger: { id: 't' }, data: [{ date: '2026-10-27', ...summary }], summary };
30
+ const sdk = new CentraliSDK({ baseUrl: 'https://example.com', workspaceId: 'acme', token: 'test', axiosConfig: {
31
+ adapter: async config => ({ data: config.url.endsWith('/trend') ? trend : list, status: 200, statusText: 'OK', headers: {}, config }),
32
+ } });
33
+ registerInsightTools({ tool: (name, description, schema, handler) => tools.set(name, handler) }, sdk);
34
+ const handle = tools.get('get_trigger_health');
35
+ assert.deepEqual(JSON.parse((await handle({ period: 7 })).content[0].text), list);
36
+ assert.deepEqual(JSON.parse((await handle({ triggerId: 't', period: 7 })).content[0].text).summary, summary);
37
+ });