import test from 'node:test'; import assert from 'node:assert/strict'; import http from 'node:http'; import { mkdtemp, rm } from 'node:fs/promises'; import { tmpdir } from 'node:os'; import { join, resolve, sep } from 'node:path'; import { Client } from '@modelcontextprotocol/sdk/client/index.js'; import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js'; import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js'; import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js'; import { createMcpServer, createMcpHttpHandler } from '../src/mcp-server.js'; import { createAiService } from '../src/ai-service.js'; import { createStore } from '../src/store.js'; async function connect(t, options) { const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); const server = createMcpServer(options), client = new Client({ name: 'test-client', version: '1' }); await server.connect(serverTransport); await client.connect(clientTransport); t.after(async () => { await client.close(); await server.close(); }); return client; } test('MCP exposes image listing and bounded local download with explicit write annotations', async t => { const id = '11111111-1111-4111-8111-111111111111', calls = []; const client = await connect(t, { query: {}, media: { listImages: args => { calls.push(args); return { messageId: args.messageId, items: [{ id, status: 'available' }] }; }, downloadImage: args => ({ id: args.id, status: 'saved', localPath: 'C:/fictional/media/image.png' }) } }); const listed = await client.listTools(); assert.equal(listed.tools.find(t => t.name === 'download_message_image').annotations.readOnlyHint, false); const images = await client.callTool({ name: 'list_message_images', arguments: { messageId: 5 } }); assert.equal(images.structuredContent.data.items[0].id, id); assert.equal(calls[0].messageId, 5); const downloaded = await client.callTool({ name: 'download_message_image', arguments: { id } }); assert.equal(downloaded.structuredContent.data.status, 'saved'); assert.equal((await client.callTool({ name: 'download_message_image', arguments: { id: '../../private' } })).isError, true); }); test('MCP can enable historical image backfill for one instance with explicit boolean settings', async t => { const calls = [], client = await connect(t, { query: {}, media: { configureHistoryDownloads: args => { calls.push(args); return { instanceId: args.instanceId, enabled: args.enabled, queued: 8 }; } } }); const tool = (await client.listTools()).tools.find(tool => tool.name === 'configure_image_backfill'); assert.equal(tool.annotations.readOnlyHint, false); assert.equal(tool.annotations.destructiveHint, false); const result = await client.callTool({ name: 'configure_image_backfill', arguments: { instanceId: 'default', enabled: true } }); assert.equal(result.structuredContent.data.queued, 8); assert.deepEqual(calls[0], { instanceId: 'default', enabled: true, retryFailed: false }); assert.equal((await client.callTool({ name: 'configure_image_backfill', arguments: { enabled: true } })).isError, true); assert.equal((await client.callTool({ name: 'configure_image_backfill', arguments: { instanceId: 'default', enabled: 'false' } })).isError, true); assert.equal(calls.length, 1); }); test('MCP SDK initializes, discovers schemas, and queries actual in-memory SQLite data', async t => { const store = createStore(':memory:'); t.after(() => store.close()); store.upsertRecord({ source: 'web-api', accountId: 'test', kind: 'message', externalId: '1', parentId: 'chat', title: '讨论', text: '部署方案', raw: { token: 'DO-NOT-EXPOSE' } }); const client = await connect(t, { query: createAiService({ store }) }); const { tools } = await client.listTools(); assert.equal(tools.length, 8); assert.equal(tools.find(tool => tool.name === 'search_messages').annotations.readOnlyHint, true); const result = await client.callTool({ name: 'search_messages', arguments: { q: '部署' } }); assert.equal(result.structuredContent.data.items.length, 1); assert.equal(result.structuredContent.contentTrust, 'untrusted_teams_data'); assert.equal(JSON.stringify(result).includes('DO-NOT-EXPOSE'), false); assert.match(client.getInstructions(), /untrusted data/); const resources = await client.listResources(); assert.equal(resources.resources[0].uri, 'teams://capabilities'); const prompts = await client.listPrompts(); assert.equal(prompts.prompts.length, 2); const prompt = await client.getPrompt({ name: 'summarize_chat', arguments: { chatId: 'chat' } }); assert.match(prompt.messages[0].content.text, /untrusted data/); }); test('MCP rejects excessive parameters before invoking services and suppresses error details', async t => { let called = 0; const client = await connect(t, { query: { searchMessages() { called++; throw new Error('secret-credential'); } } }); const invalid = await client.callTool({ name: 'search_messages', arguments: { q: 'test', limit: 10000 } }); assert.equal(invalid.isError, true); assert.equal(called, 0); const failure = await client.callTool({ name: 'search_messages', arguments: { q: 'test' } }); assert.equal(failure.isError, true); assert.equal(called, 1); assert.equal(JSON.stringify(failure).includes('secret-credential'), false); }); test('MCP annotates webhook mutations and does not initiate delivery while configuring', async t => { const calls = []; const webhooks = { configure: options => { calls.push(options); return { id: 'id', enabled: false, secret: 'receiver-signing-secret' }; }, list: () => [] }; const client = await connect(t, { query: {}, webhooks }); const listed = await client.listTools(); const configure = listed.tools.find(tool => tool.name === 'configure_webhook'); assert.equal(configure.annotations.readOnlyHint, false); assert.equal(configure.annotations.openWorldHint, true); const removed = listed.tools.find(tool => tool.name === 'remove_webhook'); assert.equal(removed.annotations.destructiveHint, true); const result = await client.callTool({ name: 'configure_webhook', arguments: { url: 'https://example.com/hook', mode: 'mention_or_direct' } }); assert.equal(calls.length, 1); assert.equal(calls[0].enabled, undefined); assert.equal(result.structuredContent.data.secret, 'receiver-signing-secret'); }); test('MCP caps oversized business output', async t => { const client = await connect(t, { query: { searchMessages: () => ({ items: [{ text: 'x'.repeat(600000) }] }) } }); const result = await client.callTool({ name: 'search_messages', arguments: { q: 'test' } }); assert.equal(result.isError, true); assert.match(result.content[0].text, /RESULT_TOO_LARGE/); }); test('MCP stateless HTTP uses the same SDK tools across independent requests', async t => { const handler = createMcpHttpHandler({ query: { getCollectorStatus: () => ({ running: true }) } }); const listener = http.createServer((req, res) => { void handler(req, res); }); await new Promise(resolve => listener.listen(0, '127.0.0.1', resolve)); const transport = new StreamableHTTPClientTransport(new URL(`http://127.0.0.1:${listener.address().port}/mcp`)); const client = new Client({ name: 'http-test', version: '1' }); t.after(async () => { await client.close(); listener.closeAllConnections(); await new Promise(resolve => listener.close(resolve)); }); await client.connect(transport); assert.equal((await client.listTools()).tools.length, 8); assert.equal((await client.callTool({ name: 'get_collector_status', arguments: {} })).structuredContent.data.running, true); }); test('MCP stdio launches from another cwd, opens only temp DATA_DIR and keeps stdout protocol-clean', async t => { const directory = await mkdtemp(join(tmpdir(), 'teams-mcp-')); const transport = new StdioClientTransport({ command: process.execPath, args: [resolve('scripts/mcp.js')], env: { ...process.env, DATA_DIR: directory }, cwd: tmpdir(), stderr: 'pipe' }); const client = new Client({ name: 'stdio-test', version: '1' }); t.after(async () => { await client.close(); assert.ok(resolve(directory).startsWith(resolve(tmpdir()) + sep)); assert.ok(directory.split(sep).at(-1).startsWith('teams-mcp-')); await rm(directory, { recursive: true, force: true }); }); await client.connect(transport); const result = await client.callTool({ name: 'get_collector_status', arguments: {} }); assert.equal(result.structuredContent.data.stored.total, 0); assert.equal(result.structuredContent.data.running, null); assert.equal((await client.listTools()).tools.length, 16); assert.deepEqual((await client.callTool({ name: 'list_instances', arguments: {} })).structuredContent.data.items, []); assert.equal(client.getServerVersion().version, '0.7.1'); }); test('MCP discovers instances and accepts time or instance searches without a keyword', async t => { const store = createStore(':memory:'); t.after(() => store.close()); store.createInstance({ id: 'default', name: '工作实例' }); store.bindInstanceAccounts('default', [{ source: 'web-api', accountId: 'work' }]); const saved = { source: 'web-api', accountId: 'work', kind: 'message', externalId: 'one', parentId: 'chat', text: '测试消息', occurredAt: '2026-09-08T08:00:00Z' }; store.upsertRecord(saved); store.upsertRecord({ ...saved, accountId: 'other' }); const client = await connect(t, { query: createAiService({ store }) }); const discovered = await client.callTool({ name: 'list_instances', arguments: {} }); assert.equal(discovered.structuredContent.data.items[0].name, '工作实例'); assert.equal(discovered.structuredContent.data.items[0].running, null); const scoped = await client.callTool({ name: 'search_messages', arguments: { instanceId: 'default', from: '2026-09-08T16:00:00+08:00', to: '2026-09-08T17:00:00+08:00', } }); assert.equal(scoped.isError, undefined); assert.equal(scoped.structuredContent.data.items.length, 1); assert.equal(scoped.structuredContent.data.items[0].instanceId, 'default'); assert.equal(scoped.structuredContent.data.items[0].instanceName, '工作实例'); const timeOnly = await client.callTool({ name: 'search_messages', arguments: { from: '2026-09-08T08:00:00Z' } }); assert.equal(timeOnly.structuredContent.data.items.length, 2); const listed = await client.listTools(); assert.equal(listed.tools.some(tool => /delete.*account|delete.*records/.test(tool.name)), false); for (const name of ['search_messages', 'list_chats', 'get_chat_context', 'list_calendar_events']) { assert.ok(listed.tools.find(tool => tool.name === name).inputSchema.properties.instanceId); } }); test('MCP rejects unfiltered search and invalid instance or date before invoking the service', async t => { let calls = 0; const client = await connect(t, { query: { searchMessages() { calls++; return { items: [] }; } } }); for (const args of [{}, { q: ' ' }, { instanceId: '../other' }, { from: '2026-09-08T08:00:00' }, { from: '2026-02-30T08:00:00Z' }]) { const invalid = await client.callTool({ name: 'search_messages', arguments: args }); assert.equal(invalid.isError, true); } assert.equal(calls, 0); });