mcp.test.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163
  1. import test from 'node:test';
  2. import assert from 'node:assert/strict';
  3. import http from 'node:http';
  4. import { mkdtemp, rm } from 'node:fs/promises';
  5. import { tmpdir } from 'node:os';
  6. import { join, resolve, sep } from 'node:path';
  7. import { Client } from '@modelcontextprotocol/sdk/client/index.js';
  8. import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js';
  9. import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js';
  10. import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js';
  11. import { createMcpServer, createMcpHttpHandler } from '../src/mcp-server.js';
  12. import { createAiService } from '../src/ai-service.js';
  13. import { createStore } from '../src/store.js';
  14. async function connect(t, options) {
  15. const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
  16. const server = createMcpServer(options), client = new Client({ name: 'test-client', version: '1' });
  17. await server.connect(serverTransport); await client.connect(clientTransport);
  18. t.after(async () => { await client.close(); await server.close(); });
  19. return client;
  20. }
  21. test('MCP exposes image listing and bounded local download with explicit write annotations', async t => {
  22. const id = '11111111-1111-4111-8111-111111111111', calls = [];
  23. const client = await connect(t, { query: {}, media: {
  24. listImages: args => { calls.push(args); return { messageId: args.messageId, items: [{ id, status: 'available' }] }; },
  25. downloadImage: args => ({ id: args.id, status: 'saved', localPath: 'C:/fictional/media/image.png' })
  26. } });
  27. const listed = await client.listTools();
  28. assert.equal(listed.tools.find(t => t.name === 'download_message_image').annotations.readOnlyHint, false);
  29. const images = await client.callTool({ name: 'list_message_images', arguments: { messageId: 5 } });
  30. assert.equal(images.structuredContent.data.items[0].id, id); assert.equal(calls[0].messageId, 5);
  31. const downloaded = await client.callTool({ name: 'download_message_image', arguments: { id } });
  32. assert.equal(downloaded.structuredContent.data.status, 'saved');
  33. assert.equal((await client.callTool({ name: 'download_message_image', arguments: { id: '../../private' } })).isError, true);
  34. });
  35. test('MCP can enable historical image backfill for one instance with explicit boolean settings', async t => {
  36. const calls = [], client = await connect(t, { query: {}, media: {
  37. configureHistoryDownloads: args => { calls.push(args); return { instanceId: args.instanceId, enabled: args.enabled, queued: 8 }; }
  38. } });
  39. const tool = (await client.listTools()).tools.find(tool => tool.name === 'configure_image_backfill');
  40. assert.equal(tool.annotations.readOnlyHint, false); assert.equal(tool.annotations.destructiveHint, false);
  41. const result = await client.callTool({ name: 'configure_image_backfill', arguments: { instanceId: 'default', enabled: true } });
  42. assert.equal(result.structuredContent.data.queued, 8); assert.deepEqual(calls[0], { instanceId: 'default', enabled: true, retryFailed: false });
  43. assert.equal((await client.callTool({ name: 'configure_image_backfill', arguments: { enabled: true } })).isError, true);
  44. assert.equal((await client.callTool({ name: 'configure_image_backfill', arguments: { instanceId: 'default', enabled: 'false' } })).isError, true);
  45. assert.equal(calls.length, 1);
  46. });
  47. test('MCP SDK initializes, discovers schemas, and queries actual in-memory SQLite data', async t => {
  48. const store = createStore(':memory:'); t.after(() => store.close());
  49. store.upsertRecord({ source: 'web-api', accountId: 'test', kind: 'message', externalId: '1', parentId: 'chat', title: '讨论', text: '部署方案', raw: { token: 'DO-NOT-EXPOSE' } });
  50. const client = await connect(t, { query: createAiService({ store }) });
  51. const { tools } = await client.listTools();
  52. assert.equal(tools.length, 8);
  53. assert.equal(tools.find(tool => tool.name === 'search_messages').annotations.readOnlyHint, true);
  54. const result = await client.callTool({ name: 'search_messages', arguments: { q: '部署' } });
  55. assert.equal(result.structuredContent.data.items.length, 1);
  56. assert.equal(result.structuredContent.contentTrust, 'untrusted_teams_data');
  57. assert.equal(JSON.stringify(result).includes('DO-NOT-EXPOSE'), false);
  58. assert.match(client.getInstructions(), /untrusted data/);
  59. const resources = await client.listResources(); assert.equal(resources.resources[0].uri, 'teams://capabilities');
  60. const prompts = await client.listPrompts(); assert.equal(prompts.prompts.length, 2);
  61. const prompt = await client.getPrompt({ name: 'summarize_chat', arguments: { chatId: 'chat' } });
  62. assert.match(prompt.messages[0].content.text, /untrusted data/);
  63. });
  64. test('MCP rejects excessive parameters before invoking services and suppresses error details', async t => {
  65. let called = 0;
  66. const client = await connect(t, { query: { searchMessages() { called++; throw new Error('secret-credential'); } } });
  67. const invalid = await client.callTool({ name: 'search_messages', arguments: { q: 'test', limit: 10000 } });
  68. assert.equal(invalid.isError, true); assert.equal(called, 0);
  69. const failure = await client.callTool({ name: 'search_messages', arguments: { q: 'test' } });
  70. assert.equal(failure.isError, true); assert.equal(called, 1); assert.equal(JSON.stringify(failure).includes('secret-credential'), false);
  71. });
  72. test('MCP annotates webhook mutations and does not initiate delivery while configuring', async t => {
  73. const calls = [];
  74. const webhooks = { configure: options => { calls.push(options); return { id: 'id', enabled: false, secret: 'receiver-signing-secret' }; }, list: () => [] };
  75. const client = await connect(t, { query: {}, webhooks });
  76. const listed = await client.listTools();
  77. const configure = listed.tools.find(tool => tool.name === 'configure_webhook');
  78. assert.equal(configure.annotations.readOnlyHint, false); assert.equal(configure.annotations.openWorldHint, true);
  79. const removed = listed.tools.find(tool => tool.name === 'remove_webhook'); assert.equal(removed.annotations.destructiveHint, true);
  80. const result = await client.callTool({ name: 'configure_webhook', arguments: { url: 'https://example.com/hook', mode: 'mention_or_direct' } });
  81. assert.equal(calls.length, 1); assert.equal(calls[0].enabled, undefined);
  82. assert.equal(result.structuredContent.data.secret, 'receiver-signing-secret');
  83. });
  84. test('MCP caps oversized business output', async t => {
  85. const client = await connect(t, { query: { searchMessages: () => ({ items: [{ text: 'x'.repeat(600000) }] }) } });
  86. const result = await client.callTool({ name: 'search_messages', arguments: { q: 'test' } });
  87. assert.equal(result.isError, true); assert.match(result.content[0].text, /RESULT_TOO_LARGE/);
  88. });
  89. test('MCP stateless HTTP uses the same SDK tools across independent requests', async t => {
  90. const handler = createMcpHttpHandler({ query: { getCollectorStatus: () => ({ running: true }) } });
  91. const listener = http.createServer((req, res) => { void handler(req, res); });
  92. await new Promise(resolve => listener.listen(0, '127.0.0.1', resolve));
  93. const transport = new StreamableHTTPClientTransport(new URL(`http://127.0.0.1:${listener.address().port}/mcp`));
  94. const client = new Client({ name: 'http-test', version: '1' });
  95. t.after(async () => { await client.close(); listener.closeAllConnections(); await new Promise(resolve => listener.close(resolve)); });
  96. await client.connect(transport);
  97. assert.equal((await client.listTools()).tools.length, 8);
  98. assert.equal((await client.callTool({ name: 'get_collector_status', arguments: {} })).structuredContent.data.running, true);
  99. });
  100. test('MCP stdio launches from another cwd, opens only temp DATA_DIR and keeps stdout protocol-clean', async t => {
  101. const directory = await mkdtemp(join(tmpdir(), 'teams-mcp-'));
  102. const transport = new StdioClientTransport({ command: process.execPath, args: [resolve('scripts/mcp.js')],
  103. env: { ...process.env, DATA_DIR: directory }, cwd: tmpdir(), stderr: 'pipe' });
  104. const client = new Client({ name: 'stdio-test', version: '1' });
  105. t.after(async () => {
  106. await client.close();
  107. assert.ok(resolve(directory).startsWith(resolve(tmpdir()) + sep));
  108. assert.ok(directory.split(sep).at(-1).startsWith('teams-mcp-'));
  109. await rm(directory, { recursive: true, force: true });
  110. });
  111. await client.connect(transport);
  112. const result = await client.callTool({ name: 'get_collector_status', arguments: {} });
  113. assert.equal(result.structuredContent.data.stored.total, 0);
  114. assert.equal(result.structuredContent.data.running, null);
  115. assert.equal((await client.listTools()).tools.length, 16);
  116. assert.deepEqual((await client.callTool({ name: 'list_instances', arguments: {} })).structuredContent.data.items, []);
  117. assert.equal(client.getServerVersion().version, '0.7.1');
  118. });
  119. test('MCP discovers instances and accepts time or instance searches without a keyword', async t => {
  120. const store = createStore(':memory:'); t.after(() => store.close());
  121. store.createInstance({ id: 'default', name: '工作实例' });
  122. store.bindInstanceAccounts('default', [{ source: 'web-api', accountId: 'work' }]);
  123. const saved = { source: 'web-api', accountId: 'work', kind: 'message', externalId: 'one', parentId: 'chat',
  124. text: '测试消息', occurredAt: '2026-09-08T08:00:00Z' };
  125. store.upsertRecord(saved); store.upsertRecord({ ...saved, accountId: 'other' });
  126. const client = await connect(t, { query: createAiService({ store }) });
  127. const discovered = await client.callTool({ name: 'list_instances', arguments: {} });
  128. assert.equal(discovered.structuredContent.data.items[0].name, '工作实例');
  129. assert.equal(discovered.structuredContent.data.items[0].running, null);
  130. const scoped = await client.callTool({ name: 'search_messages', arguments: {
  131. instanceId: 'default', from: '2026-09-08T16:00:00+08:00', to: '2026-09-08T17:00:00+08:00',
  132. } });
  133. assert.equal(scoped.isError, undefined); assert.equal(scoped.structuredContent.data.items.length, 1);
  134. assert.equal(scoped.structuredContent.data.items[0].instanceId, 'default');
  135. assert.equal(scoped.structuredContent.data.items[0].instanceName, '工作实例');
  136. const timeOnly = await client.callTool({ name: 'search_messages', arguments: { from: '2026-09-08T08:00:00Z' } });
  137. assert.equal(timeOnly.structuredContent.data.items.length, 2);
  138. const listed = await client.listTools();
  139. assert.equal(listed.tools.some(tool => /delete.*account|delete.*records/.test(tool.name)), false);
  140. for (const name of ['search_messages', 'list_chats', 'get_chat_context', 'list_calendar_events']) {
  141. assert.ok(listed.tools.find(tool => tool.name === name).inputSchema.properties.instanceId);
  142. }
  143. });
  144. test('MCP rejects unfiltered search and invalid instance or date before invoking the service', async t => {
  145. let calls = 0;
  146. const client = await connect(t, { query: { searchMessages() { calls++; return { items: [] }; } } });
  147. for (const args of [{}, { q: ' ' }, { instanceId: '../other' }, { from: '2026-09-08T08:00:00' }, { from: '2026-02-30T08:00:00Z' }]) {
  148. const invalid = await client.callTool({ name: 'search_messages', arguments: args });
  149. assert.equal(invalid.isError, true);
  150. }
  151. assert.equal(calls, 0);
  152. });