@dxos/introspect-mcp 0.0.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.
- package/README.md +212 -0
- package/bin/dx-introspect-mcp.mjs +11 -0
- package/dist/lib/node-esm/chunk-63HTIHM3.mjs +400 -0
- package/dist/lib/node-esm/chunk-63HTIHM3.mjs.map +7 -0
- package/dist/lib/node-esm/index.mjs +270 -0
- package/dist/lib/node-esm/index.mjs.map +7 -0
- package/dist/lib/node-esm/meta.json +1 -0
- package/dist/lib/node-esm/tools/index.mjs +34 -0
- package/dist/lib/node-esm/tools/index.mjs.map +7 -0
- package/dist/types/src/cli.d.ts +2 -0
- package/dist/types/src/cli.d.ts.map +1 -0
- package/dist/types/src/index.d.ts +3 -0
- package/dist/types/src/index.d.ts.map +1 -0
- package/dist/types/src/server/http.test.d.ts +2 -0
- package/dist/types/src/server/http.test.d.ts.map +1 -0
- package/dist/types/src/server/index.d.ts +3 -0
- package/dist/types/src/server/index.d.ts.map +1 -0
- package/dist/types/src/server/main.d.ts +2 -0
- package/dist/types/src/server/main.d.ts.map +1 -0
- package/dist/types/src/server/server.d.ts +14 -0
- package/dist/types/src/server/server.d.ts.map +1 -0
- package/dist/types/src/server/server.test.d.ts +2 -0
- package/dist/types/src/server/server.test.d.ts.map +1 -0
- package/dist/types/src/server/stdio.test.d.ts +2 -0
- package/dist/types/src/server/stdio.test.d.ts.map +1 -0
- package/dist/types/src/tools/index.d.ts +4 -0
- package/dist/types/src/tools/index.d.ts.map +1 -0
- package/dist/types/src/tools/logger.d.ts +20 -0
- package/dist/types/src/tools/logger.d.ts.map +1 -0
- package/dist/types/src/tools/shaping.d.ts +24 -0
- package/dist/types/src/tools/shaping.d.ts.map +1 -0
- package/dist/types/src/tools/tools.d.ts +38 -0
- package/dist/types/src/tools/tools.d.ts.map +1 -0
- package/dist/types/src/tools/tools.test.d.ts +2 -0
- package/dist/types/src/tools/tools.test.d.ts.map +1 -0
- package/dist/types/tsconfig.tsbuildinfo +1 -0
- package/package.json +53 -0
- package/src/cli.ts +13 -0
- package/src/index.ts +10 -0
- package/src/server/http.test.ts +89 -0
- package/src/server/index.ts +10 -0
- package/src/server/main.ts +275 -0
- package/src/server/server.test.ts +215 -0
- package/src/server/server.ts +79 -0
- package/src/server/stdio.test.ts +76 -0
- package/src/tools/index.ts +28 -0
- package/src/tools/logger.ts +60 -0
- package/src/tools/shaping.ts +194 -0
- package/src/tools/tools.test.ts +78 -0
- package/src/tools/tools.ts +212 -0
package/package.json
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@dxos/introspect-mcp",
|
|
3
|
+
"version": "0.0.0",
|
|
4
|
+
"description": "MCP server exposing DXOS monorepo introspection.",
|
|
5
|
+
"homepage": "https://dxos.org",
|
|
6
|
+
"bugs": "https://github.com/dxos/dxos/issues",
|
|
7
|
+
"repository": {
|
|
8
|
+
"type": "git",
|
|
9
|
+
"url": "https://github.com/dxos/dxos"
|
|
10
|
+
},
|
|
11
|
+
"license": "MIT",
|
|
12
|
+
"author": "info@dxos.org",
|
|
13
|
+
"type": "module",
|
|
14
|
+
"exports": {
|
|
15
|
+
".": {
|
|
16
|
+
"source": "./src/index.ts",
|
|
17
|
+
"types": "./dist/types/src/index.d.ts",
|
|
18
|
+
"default": "./dist/lib/node/index.mjs"
|
|
19
|
+
},
|
|
20
|
+
"./tools": {
|
|
21
|
+
"source": "./src/tools/index.ts",
|
|
22
|
+
"types": "./dist/types/src/tools/index.d.ts",
|
|
23
|
+
"default": "./dist/lib/node/tools/index.mjs"
|
|
24
|
+
}
|
|
25
|
+
},
|
|
26
|
+
"bin": {
|
|
27
|
+
"dx-introspect-mcp": "./bin/dx-introspect-mcp.mjs"
|
|
28
|
+
},
|
|
29
|
+
"files": [
|
|
30
|
+
"bin",
|
|
31
|
+
"dist",
|
|
32
|
+
"src"
|
|
33
|
+
],
|
|
34
|
+
"scripts": {
|
|
35
|
+
"start": "tsx --conditions=source src/cli.ts"
|
|
36
|
+
},
|
|
37
|
+
"dependencies": {
|
|
38
|
+
"@dxos/effect-zod": "workspace:*",
|
|
39
|
+
"@dxos/introspect": "workspace:*",
|
|
40
|
+
"@dxos/introspect-tools": "workspace:*",
|
|
41
|
+
"@dxos/log": "workspace:*",
|
|
42
|
+
"@dxos/util": "workspace:*",
|
|
43
|
+
"@modelcontextprotocol/sdk": "catalog:",
|
|
44
|
+
"effect": "catalog:",
|
|
45
|
+
"zod": "catalog:"
|
|
46
|
+
},
|
|
47
|
+
"devDependencies": {
|
|
48
|
+
"@types/node": "catalog:",
|
|
49
|
+
"tsx": "catalog:",
|
|
50
|
+
"typescript": "catalog:",
|
|
51
|
+
"vitest": "catalog:"
|
|
52
|
+
}
|
|
53
|
+
}
|
package/src/cli.ts
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
//
|
|
2
|
+
// Copyright 2026 DXOS.org
|
|
3
|
+
//
|
|
4
|
+
|
|
5
|
+
// TODO(burdon): Consider how to integrate with DXOS CLI.
|
|
6
|
+
// Direct CLI entry — invoked by `pnpm -F @dxos/introspect-mcp start` via tsx.
|
|
7
|
+
|
|
8
|
+
import { main } from './server';
|
|
9
|
+
|
|
10
|
+
main().catch((err) => {
|
|
11
|
+
console.error(err);
|
|
12
|
+
process.exit(1);
|
|
13
|
+
});
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
//
|
|
2
|
+
// Copyright 2026 DXOS.org
|
|
3
|
+
//
|
|
4
|
+
|
|
5
|
+
// Top-level barrel: the MCP server. Tool definitions are also re-exported
|
|
6
|
+
// here for convenience, but consumers wanting only the tools (without the
|
|
7
|
+
// stdio/HTTP server) should import from `@dxos/introspect-mcp/tools`.
|
|
8
|
+
|
|
9
|
+
export { createServer, main, type ServerOptions } from './server';
|
|
10
|
+
export { fileLogger, noopLogger, type ToolLogEntry, type ToolLogger } from './tools';
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
//
|
|
2
|
+
// Copyright 2026 DXOS.org
|
|
3
|
+
//
|
|
4
|
+
|
|
5
|
+
// End-to-end HTTP integration test: boots the CLI as a subprocess in --http
|
|
6
|
+
// mode, connects via the SDK's StreamableHTTPClientTransport, exercises tool
|
|
7
|
+
// calls. Catches transport-specific failures (auth handling, body parsing,
|
|
8
|
+
// session semantics) that the stdio test can't.
|
|
9
|
+
|
|
10
|
+
import { Client } from '@modelcontextprotocol/sdk/client/index.js';
|
|
11
|
+
import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js';
|
|
12
|
+
import { spawn } from 'node:child_process';
|
|
13
|
+
import { dirname, join } from 'node:path';
|
|
14
|
+
import { fileURLToPath } from 'node:url';
|
|
15
|
+
import { afterAll, beforeAll, describe, test } from 'vitest';
|
|
16
|
+
|
|
17
|
+
const __dirname = dirname(fileURLToPath(import.meta.url));
|
|
18
|
+
// cli.ts lives at src/cli.ts (kept at the package's public entry path so
|
|
19
|
+
// .mcp.json / moon tasks / scripts can keep referencing it unchanged).
|
|
20
|
+
const CLI_PATH = join(__dirname, '..', 'cli.ts');
|
|
21
|
+
const FIXTURE_ROOT = join(__dirname, '..', '..', '..', 'introspect', 'src', '__fixtures__');
|
|
22
|
+
|
|
23
|
+
// Pick a high port that's unlikely to collide with a running dev tool.
|
|
24
|
+
const PORT = 39476;
|
|
25
|
+
// Force IPv4 — `localhost` resolves to ::1 first on Linux containers, which
|
|
26
|
+
// breaks fetch() if the server bound to 127.0.0.1 (or vice versa).
|
|
27
|
+
const HOST = '127.0.0.1';
|
|
28
|
+
|
|
29
|
+
describe('http integration', () => {
|
|
30
|
+
let serverProcess: ReturnType<typeof spawn>;
|
|
31
|
+
let client: Client;
|
|
32
|
+
|
|
33
|
+
beforeAll(async () => {
|
|
34
|
+
const tsx = join(FIXTURE_ROOT, '..', '..', '..', '..', '..', 'node_modules', '.bin', 'tsx');
|
|
35
|
+
serverProcess = spawn(
|
|
36
|
+
tsx,
|
|
37
|
+
['--conditions=source', CLI_PATH, '--root', FIXTURE_ROOT, '--http', String(PORT), '--host', HOST],
|
|
38
|
+
{ stdio: ['ignore', 'pipe', 'pipe'] },
|
|
39
|
+
);
|
|
40
|
+
|
|
41
|
+
// Wait for the "HTTP server listening" line on stderr.
|
|
42
|
+
await new Promise<void>((resolveListen, rejectListen) => {
|
|
43
|
+
const onErr = (chunk: Buffer) => {
|
|
44
|
+
if (chunk.toString().includes('HTTP server listening')) {
|
|
45
|
+
serverProcess.stderr?.off('data', onErr);
|
|
46
|
+
resolveListen();
|
|
47
|
+
}
|
|
48
|
+
};
|
|
49
|
+
serverProcess.stderr?.on('data', onErr);
|
|
50
|
+
serverProcess.once('error', rejectListen);
|
|
51
|
+
setTimeout(() => rejectListen(new Error('server did not start within 30s')), 30_000);
|
|
52
|
+
});
|
|
53
|
+
|
|
54
|
+
const transport = new StreamableHTTPClientTransport(new URL(`http://${HOST}:${PORT}/mcp`));
|
|
55
|
+
client = new Client({ name: 'http-probe', version: 'test' }, { capabilities: {} });
|
|
56
|
+
await client.connect(transport);
|
|
57
|
+
}, 60_000);
|
|
58
|
+
|
|
59
|
+
afterAll(async () => {
|
|
60
|
+
await client?.close().catch(() => undefined);
|
|
61
|
+
serverProcess?.kill('SIGTERM');
|
|
62
|
+
});
|
|
63
|
+
|
|
64
|
+
test('subprocess starts in HTTP mode and lists every registered tool', async ({ expect }) => {
|
|
65
|
+
const { tools } = await client.listTools();
|
|
66
|
+
const names = tools.map((t) => t.name).sort();
|
|
67
|
+
expect(names).toEqual([
|
|
68
|
+
'find_symbol',
|
|
69
|
+
'get_package',
|
|
70
|
+
'get_symbol',
|
|
71
|
+
'list_capabilities',
|
|
72
|
+
'list_operations',
|
|
73
|
+
'list_packages',
|
|
74
|
+
'list_plugins',
|
|
75
|
+
'list_schemas',
|
|
76
|
+
'list_surfaces',
|
|
77
|
+
'list_symbols',
|
|
78
|
+
]);
|
|
79
|
+
});
|
|
80
|
+
|
|
81
|
+
test('list_packages round-trips JSON-RPC over HTTP', async ({ expect }) => {
|
|
82
|
+
const result = (await client.callTool({ name: 'list_packages', arguments: {} })) as {
|
|
83
|
+
content: Array<{ type: string; text?: string }>;
|
|
84
|
+
};
|
|
85
|
+
const text = result.content.find((c) => c.type === 'text')?.text ?? '';
|
|
86
|
+
const payload = JSON.parse(text) as { data: Array<{ name: string }> };
|
|
87
|
+
expect(payload.data.map((p) => p.name)).toContain('@fixture/pkg-a');
|
|
88
|
+
});
|
|
89
|
+
});
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
//
|
|
2
|
+
// Copyright 2026 DXOS.org
|
|
3
|
+
//
|
|
4
|
+
|
|
5
|
+
// MCP server wiring — transport (stdio / HTTP), tool registration loop, the
|
|
6
|
+
// readiness gate. Tool *definitions* live in `../tools` so they can be
|
|
7
|
+
// embedded into a different MCP runtime without dragging in this server.
|
|
8
|
+
|
|
9
|
+
export { createServer, type ServerOptions } from './server';
|
|
10
|
+
export { main } from './main';
|
|
@@ -0,0 +1,275 @@
|
|
|
1
|
+
//
|
|
2
|
+
// Copyright 2026 DXOS.org
|
|
3
|
+
//
|
|
4
|
+
|
|
5
|
+
// Entry point for the dx-introspect-mcp CLI. Boots an introspector against the
|
|
6
|
+
// monorepo root inferred from cwd (or --root) and exposes it over either
|
|
7
|
+
// stdio (default) or HTTP (when --http <port> is passed).
|
|
8
|
+
|
|
9
|
+
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
|
|
10
|
+
import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';
|
|
11
|
+
import { randomUUID } from 'node:crypto';
|
|
12
|
+
import { existsSync } from 'node:fs';
|
|
13
|
+
import { createServer as createHttpServer, type IncomingMessage, type ServerResponse } from 'node:http';
|
|
14
|
+
import { dirname, isAbsolute, resolve } from 'node:path';
|
|
15
|
+
|
|
16
|
+
import { createIntrospector } from '@dxos/introspect';
|
|
17
|
+
|
|
18
|
+
import { fileLogger } from '../tools';
|
|
19
|
+
import { createServer } from './server';
|
|
20
|
+
|
|
21
|
+
type Args = {
|
|
22
|
+
root: string;
|
|
23
|
+
logPath?: string;
|
|
24
|
+
/** If set, run as an HTTP server on this port instead of stdio. */
|
|
25
|
+
httpPort?: number;
|
|
26
|
+
/** Bind address for HTTP mode. Defaults to localhost. */
|
|
27
|
+
host: string;
|
|
28
|
+
/** Optional bearer token; when set, requests must send `Authorization: Bearer <token>`. */
|
|
29
|
+
apiKey?: string;
|
|
30
|
+
};
|
|
31
|
+
|
|
32
|
+
const parseArgs = (argv: string[]): Args => {
|
|
33
|
+
let root: string | undefined;
|
|
34
|
+
let logPath: string | undefined;
|
|
35
|
+
let httpPort: number | undefined;
|
|
36
|
+
let host = 'localhost';
|
|
37
|
+
let apiKey: string | undefined;
|
|
38
|
+
const valueArgs = new Set(['--root', '--log-path', '--http', '--host', '--api-key']);
|
|
39
|
+
for (let i = 0; i < argv.length; i++) {
|
|
40
|
+
const arg = argv[i];
|
|
41
|
+
if (valueArgs.has(arg)) {
|
|
42
|
+
const value = argv[i + 1];
|
|
43
|
+
if (value === undefined || value.startsWith('-')) {
|
|
44
|
+
console.error(`Error: ${arg} requires a value.`);
|
|
45
|
+
printUsage();
|
|
46
|
+
process.exit(1);
|
|
47
|
+
}
|
|
48
|
+
i++;
|
|
49
|
+
switch (arg) {
|
|
50
|
+
case '--root':
|
|
51
|
+
root = value;
|
|
52
|
+
break;
|
|
53
|
+
case '--log-path':
|
|
54
|
+
logPath = value;
|
|
55
|
+
break;
|
|
56
|
+
case '--http':
|
|
57
|
+
httpPort = Number.parseInt(value, 10);
|
|
58
|
+
if (!Number.isFinite(httpPort) || httpPort <= 0) {
|
|
59
|
+
console.error(`Error: --http expects a port number, got "${value}".`);
|
|
60
|
+
process.exit(1);
|
|
61
|
+
}
|
|
62
|
+
break;
|
|
63
|
+
case '--host':
|
|
64
|
+
host = value;
|
|
65
|
+
break;
|
|
66
|
+
case '--api-key':
|
|
67
|
+
apiKey = value;
|
|
68
|
+
break;
|
|
69
|
+
}
|
|
70
|
+
} else if (arg === '--help' || arg === '-h') {
|
|
71
|
+
printUsage();
|
|
72
|
+
process.exit(0);
|
|
73
|
+
} else {
|
|
74
|
+
console.error(`Unknown argument: ${arg}`);
|
|
75
|
+
printUsage();
|
|
76
|
+
process.exit(1);
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
const resolvedRoot = root ? resolveRoot(root) : findrootPath(process.cwd());
|
|
80
|
+
if (!resolvedRoot) {
|
|
81
|
+
console.error('Could not find monorepo root (looking for pnpm-workspace.yaml). Pass --root explicitly.');
|
|
82
|
+
process.exit(1);
|
|
83
|
+
}
|
|
84
|
+
return { root: resolvedRoot, logPath, httpPort, host, apiKey };
|
|
85
|
+
};
|
|
86
|
+
|
|
87
|
+
const resolveRoot = (root: string): string => (isAbsolute(root) ? root : resolve(process.cwd(), root));
|
|
88
|
+
|
|
89
|
+
const findrootPath = (start: string): string | null => {
|
|
90
|
+
let cursor = start;
|
|
91
|
+
while (true) {
|
|
92
|
+
if (existsSync(`${cursor}/pnpm-workspace.yaml`)) {
|
|
93
|
+
return cursor;
|
|
94
|
+
}
|
|
95
|
+
const parent = dirname(cursor);
|
|
96
|
+
if (parent === cursor) {
|
|
97
|
+
return null;
|
|
98
|
+
}
|
|
99
|
+
cursor = parent;
|
|
100
|
+
}
|
|
101
|
+
};
|
|
102
|
+
|
|
103
|
+
const printUsage = (): void => {
|
|
104
|
+
console.error(
|
|
105
|
+
[
|
|
106
|
+
'Usage: dx-introspect-mcp [options]',
|
|
107
|
+
'',
|
|
108
|
+
'Options:',
|
|
109
|
+
' --root <path> Monorepo root (default: discovered from cwd via pnpm-workspace.yaml)',
|
|
110
|
+
' --log-path <path> Append-only JSONL log of tool calls (default: stderr-silent)',
|
|
111
|
+
' --http <port> Run as HTTP server on the given port (default: stdio)',
|
|
112
|
+
' --host <addr> HTTP bind address (default: localhost)',
|
|
113
|
+
' --api-key <token> Require `Authorization: Bearer <token>` on HTTP requests',
|
|
114
|
+
' -h, --help Show this help',
|
|
115
|
+
].join('\n'),
|
|
116
|
+
);
|
|
117
|
+
};
|
|
118
|
+
|
|
119
|
+
export const main = async (argv: string[] = process.argv.slice(2)): Promise<void> => {
|
|
120
|
+
const args = parseArgs(argv);
|
|
121
|
+
|
|
122
|
+
// Kick off indexing in the background. We deliberately DON'T await
|
|
123
|
+
// `introspector.ready` here — on a cold cache that's ~80s of ts-morph
|
|
124
|
+
// parsing, longer than most MCP clients (Inspector, Claude Code, Composer)
|
|
125
|
+
// will wait for `initialize` / `tools/list`. Each tool handler awaits
|
|
126
|
+
// `introspector.ready` itself before doing work, so:
|
|
127
|
+
//
|
|
128
|
+
// - `initialize` responds instantly (MCP handshake — no introspector calls)
|
|
129
|
+
// - `tools/list` responds instantly (registered statically in createServer)
|
|
130
|
+
// - `tools/call` waits for indexing, then runs
|
|
131
|
+
//
|
|
132
|
+
// Result: clients connect immediately and the first real query pays the
|
|
133
|
+
// one-time cold-start cost. Subsequent calls hit the cache and are fast.
|
|
134
|
+
const introspector = createIntrospector({ rootPath: args.root });
|
|
135
|
+
// Surface fatal indexing errors to stderr and exit. A live but
|
|
136
|
+
// permanently-unusable process is worse than a clean failure: every tool
|
|
137
|
+
// call would block forever on `await introspector.ready` once the rejected
|
|
138
|
+
// promise is awaited, leaving the MCP client hung with no signal.
|
|
139
|
+
introspector.ready.catch((err) => {
|
|
140
|
+
console.error('[introspect-mcp] indexer failed:', err);
|
|
141
|
+
process.exit(1);
|
|
142
|
+
});
|
|
143
|
+
|
|
144
|
+
const server = createServer({
|
|
145
|
+
introspector,
|
|
146
|
+
name: '@dxos/introspect-mcp',
|
|
147
|
+
version: '0.0.1',
|
|
148
|
+
logger: args.logPath ? fileLogger(args.logPath) : undefined,
|
|
149
|
+
});
|
|
150
|
+
|
|
151
|
+
if (args.httpPort !== undefined) {
|
|
152
|
+
// HTTP mode needs a fresh McpServer per session (the SDK rejects multiple
|
|
153
|
+
// transports on the same Server). Pass a factory so runHttp can build one
|
|
154
|
+
// per connection while sharing the introspector.
|
|
155
|
+
await runHttp(
|
|
156
|
+
() =>
|
|
157
|
+
createServer({
|
|
158
|
+
introspector,
|
|
159
|
+
name: '@dxos/introspect-mcp',
|
|
160
|
+
version: '0.0.1',
|
|
161
|
+
logger: args.logPath ? fileLogger(args.logPath) : undefined,
|
|
162
|
+
}),
|
|
163
|
+
args,
|
|
164
|
+
);
|
|
165
|
+
} else {
|
|
166
|
+
const transport = new StdioServerTransport();
|
|
167
|
+
await server.connect(transport);
|
|
168
|
+
// Stay alive until stdin closes — the SDK handles that signal internally.
|
|
169
|
+
}
|
|
170
|
+
};
|
|
171
|
+
|
|
172
|
+
const runHttp = async (serverFactory: () => Awaited<ReturnType<typeof createServer>>, args: Args): Promise<void> => {
|
|
173
|
+
// Stateful mode — we keep one transport per client session. The session ID
|
|
174
|
+
// is returned in the initialize response and the client echoes it on every
|
|
175
|
+
// subsequent request. Required because the MCP client expects to send
|
|
176
|
+
// `notifications/initialized` (and later requests) under the same session.
|
|
177
|
+
const transports = new Map<string, StreamableHTTPServerTransport>();
|
|
178
|
+
|
|
179
|
+
const httpServer = createHttpServer((req: IncomingMessage, res: ServerResponse) => {
|
|
180
|
+
// CORS — Composer (and any other browser-based MCP client) sends a
|
|
181
|
+
// cross-origin preflight before the POST. Without these headers, the
|
|
182
|
+
// browser blocks the request and the underlying client surfaces a generic
|
|
183
|
+
// "UnknownException" from Effect.tryPromise. We allow any origin because
|
|
184
|
+
// this server is for local dev only; it should bind to localhost.
|
|
185
|
+
res.setHeader('Access-Control-Allow-Origin', req.headers.origin ?? '*');
|
|
186
|
+
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, DELETE, OPTIONS');
|
|
187
|
+
res.setHeader(
|
|
188
|
+
'Access-Control-Allow-Headers',
|
|
189
|
+
'Content-Type, Authorization, Mcp-Session-Id, Last-Event-ID, MCP-Protocol-Version',
|
|
190
|
+
);
|
|
191
|
+
res.setHeader('Access-Control-Expose-Headers', 'Mcp-Session-Id');
|
|
192
|
+
res.setHeader('Access-Control-Max-Age', '86400');
|
|
193
|
+
res.setHeader('Vary', 'Origin');
|
|
194
|
+
if (req.method === 'OPTIONS') {
|
|
195
|
+
res.statusCode = 204;
|
|
196
|
+
res.end();
|
|
197
|
+
return;
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
// Apply optional bearer-token auth before delegating to the transport.
|
|
201
|
+
if (args.apiKey) {
|
|
202
|
+
const header = req.headers.authorization ?? '';
|
|
203
|
+
const expected = `Bearer ${args.apiKey}`;
|
|
204
|
+
if (header !== expected) {
|
|
205
|
+
res.statusCode = 401;
|
|
206
|
+
res.setHeader('WWW-Authenticate', 'Bearer');
|
|
207
|
+
res.end('Unauthorized');
|
|
208
|
+
return;
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
if (req.url === '/health') {
|
|
212
|
+
res.statusCode = 200;
|
|
213
|
+
res.setHeader('content-type', 'text/plain');
|
|
214
|
+
res.end('ok\n');
|
|
215
|
+
return;
|
|
216
|
+
}
|
|
217
|
+
if (req.url !== '/mcp' && req.url !== '/mcp/') {
|
|
218
|
+
res.statusCode = 404;
|
|
219
|
+
res.end('Not found');
|
|
220
|
+
return;
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
void (async () => {
|
|
224
|
+
const sessionId = req.headers['mcp-session-id'];
|
|
225
|
+
let transport: StreamableHTTPServerTransport | undefined;
|
|
226
|
+
if (typeof sessionId === 'string' && transports.has(sessionId)) {
|
|
227
|
+
transport = transports.get(sessionId)!;
|
|
228
|
+
} else {
|
|
229
|
+
// No session yet — must be an `initialize` request. Spin up a new
|
|
230
|
+
// McpServer + transport pair (the SDK requires a 1:1 binding) and
|
|
231
|
+
// remember it under the session id Composer/Inspector echoes back.
|
|
232
|
+
const sessionServer = serverFactory();
|
|
233
|
+
transport = new StreamableHTTPServerTransport({
|
|
234
|
+
sessionIdGenerator: () => randomUUID(),
|
|
235
|
+
onsessioninitialized: (id) => {
|
|
236
|
+
transports.set(id, transport!);
|
|
237
|
+
},
|
|
238
|
+
});
|
|
239
|
+
transport.onclose = () => {
|
|
240
|
+
if (transport!.sessionId) {
|
|
241
|
+
transports.delete(transport!.sessionId);
|
|
242
|
+
}
|
|
243
|
+
// Best-effort cleanup of the per-session server.
|
|
244
|
+
sessionServer.close().catch(() => undefined);
|
|
245
|
+
};
|
|
246
|
+
await sessionServer.connect(transport);
|
|
247
|
+
}
|
|
248
|
+
try {
|
|
249
|
+
await transport.handleRequest(req, res);
|
|
250
|
+
} catch (err) {
|
|
251
|
+
console.error('[introspect-mcp] HTTP transport error:', err);
|
|
252
|
+
if (!res.writableEnded) {
|
|
253
|
+
res.statusCode = 500;
|
|
254
|
+
res.end('Internal Server Error');
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
})();
|
|
258
|
+
});
|
|
259
|
+
|
|
260
|
+
await new Promise<void>((resolveListen, rejectListen) => {
|
|
261
|
+
httpServer.once('error', rejectListen);
|
|
262
|
+
httpServer.listen(args.httpPort, args.host, () => {
|
|
263
|
+
console.error(`[introspect-mcp] HTTP server listening on http://${args.host}:${args.httpPort}/mcp`);
|
|
264
|
+
if (args.apiKey) {
|
|
265
|
+
console.error('[introspect-mcp] auth: Authorization: Bearer <token> required');
|
|
266
|
+
} else {
|
|
267
|
+
console.error('[introspect-mcp] auth: none — bind to localhost only');
|
|
268
|
+
}
|
|
269
|
+
resolveListen();
|
|
270
|
+
});
|
|
271
|
+
});
|
|
272
|
+
|
|
273
|
+
// Stay alive until SIGINT/SIGTERM.
|
|
274
|
+
await new Promise<void>(() => {});
|
|
275
|
+
};
|
|
@@ -0,0 +1,215 @@
|
|
|
1
|
+
//
|
|
2
|
+
// Copyright 2026 DXOS.org
|
|
3
|
+
//
|
|
4
|
+
|
|
5
|
+
// In-memory server tests — verify the MCP wiring (tool registration, input
|
|
6
|
+
// validation, response shaping, readiness gate) using the introspect fixture
|
|
7
|
+
// monorepo. Plugin/schema list tools are exercised at the call-site level
|
|
8
|
+
// only (returning [] against the fixture, since pkg-a / pkg-b aren't
|
|
9
|
+
// plugins); their real-monorepo coverage lives in the sanity test.
|
|
10
|
+
|
|
11
|
+
import { Client } from '@modelcontextprotocol/sdk/client/index.js';
|
|
12
|
+
import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js';
|
|
13
|
+
import { dirname, join } from 'node:path';
|
|
14
|
+
import { fileURLToPath } from 'node:url';
|
|
15
|
+
import { afterAll, beforeAll, describe, expect, test } from 'vitest';
|
|
16
|
+
|
|
17
|
+
import { createIntrospector, type Introspector } from '@dxos/introspect';
|
|
18
|
+
|
|
19
|
+
import { createServer } from './server';
|
|
20
|
+
|
|
21
|
+
const __dirname = dirname(fileURLToPath(import.meta.url));
|
|
22
|
+
const FIXTURE_ROOT = join(__dirname, '..', '..', '..', 'introspect', 'src', '__fixtures__');
|
|
23
|
+
|
|
24
|
+
type Connected = {
|
|
25
|
+
client: Client;
|
|
26
|
+
introspector: Introspector;
|
|
27
|
+
close: () => Promise<void>;
|
|
28
|
+
};
|
|
29
|
+
|
|
30
|
+
const connect = async (): Promise<Connected> => {
|
|
31
|
+
const introspector = createIntrospector({ rootPath: FIXTURE_ROOT, cache: false });
|
|
32
|
+
await introspector.ready;
|
|
33
|
+
const server = createServer({ introspector, version: 'test' });
|
|
34
|
+
|
|
35
|
+
const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
|
|
36
|
+
const client = new Client({ name: 'test-client', version: 'test' }, { capabilities: {} });
|
|
37
|
+
|
|
38
|
+
await Promise.all([server.connect(serverTransport), client.connect(clientTransport)]);
|
|
39
|
+
|
|
40
|
+
const close = async (): Promise<void> => {
|
|
41
|
+
await client.close();
|
|
42
|
+
await server.close();
|
|
43
|
+
introspector.dispose();
|
|
44
|
+
};
|
|
45
|
+
|
|
46
|
+
return { client, introspector, close };
|
|
47
|
+
};
|
|
48
|
+
|
|
49
|
+
const parseToolText = (result: { content: Array<{ type: string; text?: string }> }): unknown => {
|
|
50
|
+
const text = result.content.find((c) => c.type === 'text')?.text ?? '';
|
|
51
|
+
return JSON.parse(text);
|
|
52
|
+
};
|
|
53
|
+
|
|
54
|
+
describe('introspect-mcp server', () => {
|
|
55
|
+
let env: Connected;
|
|
56
|
+
|
|
57
|
+
beforeAll(async () => {
|
|
58
|
+
env = await connect();
|
|
59
|
+
});
|
|
60
|
+
|
|
61
|
+
afterAll(async () => {
|
|
62
|
+
await env.close();
|
|
63
|
+
});
|
|
64
|
+
|
|
65
|
+
test('lists every registered tool', async ({ expect }) => {
|
|
66
|
+
const { tools } = await env.client.listTools();
|
|
67
|
+
const names = tools.map((t) => t.name).sort();
|
|
68
|
+
expect(names).toEqual([
|
|
69
|
+
'find_symbol',
|
|
70
|
+
'get_package',
|
|
71
|
+
'get_symbol',
|
|
72
|
+
'list_capabilities',
|
|
73
|
+
'list_operations',
|
|
74
|
+
'list_packages',
|
|
75
|
+
'list_plugins',
|
|
76
|
+
'list_schemas',
|
|
77
|
+
'list_surfaces',
|
|
78
|
+
'list_symbols',
|
|
79
|
+
]);
|
|
80
|
+
});
|
|
81
|
+
|
|
82
|
+
// ----- Packages & symbols -----
|
|
83
|
+
|
|
84
|
+
test('list_packages returns the fixture packages', async ({ expect }) => {
|
|
85
|
+
const result = await env.client.callTool({ name: 'list_packages', arguments: {} });
|
|
86
|
+
const payload = parseToolText(result as any) as { data: Array<{ name: string }> };
|
|
87
|
+
const names = payload.data.map((p) => p.name).sort();
|
|
88
|
+
expect(names).toContain('@fixture/pkg-a');
|
|
89
|
+
expect(names).toContain('@fixture/pkg-b');
|
|
90
|
+
});
|
|
91
|
+
|
|
92
|
+
test('list_packages applies the name filter', async ({ expect }) => {
|
|
93
|
+
const result = await env.client.callTool({
|
|
94
|
+
name: 'list_packages',
|
|
95
|
+
arguments: { name: 'pkg-a' },
|
|
96
|
+
});
|
|
97
|
+
const payload = parseToolText(result as any) as { data: Array<{ name: string }> };
|
|
98
|
+
expect(payload.data.map((p) => p.name)).toEqual(['@fixture/pkg-a']);
|
|
99
|
+
});
|
|
100
|
+
|
|
101
|
+
test('get_package returns detail for a known package', async ({ expect }) => {
|
|
102
|
+
const result = await env.client.callTool({
|
|
103
|
+
name: 'get_package',
|
|
104
|
+
arguments: { name: '@fixture/pkg-a' },
|
|
105
|
+
});
|
|
106
|
+
const payload = parseToolText(result as any) as {
|
|
107
|
+
data: { name: string; entryPoints: string[] } | null;
|
|
108
|
+
};
|
|
109
|
+
expect(payload.data?.name).toBe('@fixture/pkg-a');
|
|
110
|
+
expect(payload.data?.entryPoints).toContain('src/index.ts');
|
|
111
|
+
});
|
|
112
|
+
|
|
113
|
+
test('get_package returns null with note for unknown package', async ({ expect }) => {
|
|
114
|
+
const result = await env.client.callTool({
|
|
115
|
+
name: 'get_package',
|
|
116
|
+
arguments: { name: '@fixture/missing' },
|
|
117
|
+
});
|
|
118
|
+
const payload = parseToolText(result as any) as { data: null; note: string };
|
|
119
|
+
expect(payload.data).toBeNull();
|
|
120
|
+
expect(payload.note).toContain('No package');
|
|
121
|
+
});
|
|
122
|
+
|
|
123
|
+
test('list_symbols enumerates a package', async ({ expect }) => {
|
|
124
|
+
const result = await env.client.callTool({
|
|
125
|
+
name: 'list_symbols',
|
|
126
|
+
arguments: { package: '@fixture/pkg-a' },
|
|
127
|
+
});
|
|
128
|
+
const payload = parseToolText(result as any) as { data: Array<{ name: string }> };
|
|
129
|
+
const names = payload.data.map((s) => s.name).sort();
|
|
130
|
+
expect(names).toContain('Task');
|
|
131
|
+
expect(names).toContain('make');
|
|
132
|
+
});
|
|
133
|
+
|
|
134
|
+
test('find_symbol locates a known symbol', async ({ expect }) => {
|
|
135
|
+
const result = await env.client.callTool({
|
|
136
|
+
name: 'find_symbol',
|
|
137
|
+
arguments: { query: 'Task' },
|
|
138
|
+
});
|
|
139
|
+
const payload = parseToolText(result as any) as { data: Array<{ ref: string }> };
|
|
140
|
+
expect(payload.data.some((m) => m.ref === '@fixture/pkg-a#Task')).toBe(true);
|
|
141
|
+
});
|
|
142
|
+
|
|
143
|
+
test('get_symbol returns signature + summary', async ({ expect }) => {
|
|
144
|
+
const result = await env.client.callTool({
|
|
145
|
+
name: 'get_symbol',
|
|
146
|
+
arguments: { ref: '@fixture/pkg-a#make' },
|
|
147
|
+
});
|
|
148
|
+
const payload = parseToolText(result as any) as {
|
|
149
|
+
data: { ref: string; signature: string } | null;
|
|
150
|
+
};
|
|
151
|
+
expect(payload.data?.ref).toBe('@fixture/pkg-a#make');
|
|
152
|
+
expect(payload.data?.signature).toContain('make');
|
|
153
|
+
});
|
|
154
|
+
|
|
155
|
+
test('get_symbol with include=["source"] expands the body', async ({ expect }) => {
|
|
156
|
+
const result = await env.client.callTool({
|
|
157
|
+
name: 'get_symbol',
|
|
158
|
+
arguments: { ref: '@fixture/pkg-a#Task', include: ['source'] },
|
|
159
|
+
});
|
|
160
|
+
const payload = parseToolText(result as any) as { data: { source?: string } | null };
|
|
161
|
+
expect(payload.data?.source).toContain('Schema.Struct');
|
|
162
|
+
});
|
|
163
|
+
|
|
164
|
+
// ----- Plugin / surface / capability / operation / schema list tools -----
|
|
165
|
+
// Fixture monorepo has no plugins, so each call returns []. The shape
|
|
166
|
+
// matters: data must be an array, no error.
|
|
167
|
+
|
|
168
|
+
test.each([['list_plugins'], ['list_surfaces'], ['list_capabilities'], ['list_operations'], ['list_schemas']])(
|
|
169
|
+
'%s returns an empty array against the fixture monorepo',
|
|
170
|
+
async (name) => {
|
|
171
|
+
const result = await env.client.callTool({ name, arguments: {} });
|
|
172
|
+
const payload = parseToolText(result as any) as { data: unknown[] };
|
|
173
|
+
expect(Array.isArray(payload.data)).toBe(true);
|
|
174
|
+
expect(payload.data).toEqual([]);
|
|
175
|
+
},
|
|
176
|
+
);
|
|
177
|
+
|
|
178
|
+
// ----- limit + compact list options -----
|
|
179
|
+
|
|
180
|
+
test('list_symbols with `limit` overrides the default cap', async ({ expect }) => {
|
|
181
|
+
const result = await env.client.callTool({
|
|
182
|
+
name: 'list_symbols',
|
|
183
|
+
arguments: { package: '@fixture/pkg-a', limit: 1 },
|
|
184
|
+
});
|
|
185
|
+
const payload = parseToolText(result as any) as { data: Array<unknown>; truncated?: string };
|
|
186
|
+
expect(payload.data.length).toBe(1);
|
|
187
|
+
expect(payload.truncated).toBeDefined();
|
|
188
|
+
});
|
|
189
|
+
|
|
190
|
+
test('list_symbols with `compact: true` strips non-essential fields', async ({ expect }) => {
|
|
191
|
+
const compact = parseToolText(
|
|
192
|
+
(await env.client.callTool({
|
|
193
|
+
name: 'list_symbols',
|
|
194
|
+
arguments: { package: '@fixture/pkg-a', compact: true },
|
|
195
|
+
})) as any,
|
|
196
|
+
) as { data: Array<Record<string, unknown>> };
|
|
197
|
+
expect(compact.data.length).toBeGreaterThan(0);
|
|
198
|
+
const keys = Object.keys(compact.data[0]).sort();
|
|
199
|
+
expect(keys).toEqual(['name', 'ref']);
|
|
200
|
+
});
|
|
201
|
+
|
|
202
|
+
test('list_packages rejects out-of-range `limit`', async ({ expect }) => {
|
|
203
|
+
const tooSmall = (await env.client.callTool({
|
|
204
|
+
name: 'list_packages',
|
|
205
|
+
arguments: { limit: 0 },
|
|
206
|
+
})) as { isError?: boolean };
|
|
207
|
+
expect(tooSmall.isError).toBe(true);
|
|
208
|
+
|
|
209
|
+
const tooLarge = (await env.client.callTool({
|
|
210
|
+
name: 'list_packages',
|
|
211
|
+
arguments: { limit: 99999 },
|
|
212
|
+
})) as { isError?: boolean };
|
|
213
|
+
expect(tooLarge.isError).toBe(true);
|
|
214
|
+
});
|
|
215
|
+
});
|