源码快照 @ 2026-09-01 (source-only, 剔除非源码素材)
Dependency audit / audit (push) Canceled after 0s
CI / plan (push) Canceled after 0s
Gitoxide helper admission / macos-latest (push) Canceled after 0s
Gitoxide helper admission / ubuntu-latest (push) Canceled after 0s
Gitoxide helper admission / windows-latest (push) Canceled after 0s
Runtime Host peer admission / quality (push) Canceled after 0s
Windows recovery / windows_recovery (push) Canceled after 0s
CI / heavy (push) Canceled after 0s
CI / test (push) Canceled after 0s

This commit is contained in:
agent-radar committed 2026-09-01 19:05:14 +08:00
commit 7be535059e
3358 files changed
+1306357

No files matched your search

+30
View File
@@ -0,0 +1,30 @@
{
"name": "@maka/mcp",
"version": "0.1.0",
"license": "Apache-2.0",
"description": "Provider-neutral MCP client manager for Maka.",
"type": "module",
"private": true,
"exports": {
".": "./dist/index.js",
"./test-only/stdio-server": "./dist/__fixtures__/stdio-server.js"
},
"main": "./dist/index.js",
"types": "./dist/index.d.ts",
"scripts": {
"clean": "node ../../scripts/clean-paths.mjs dist tsconfig.tsbuildinfo",
"build": "tsc -p tsconfig.json",
"typecheck": "tsc -p tsconfig.json --noEmit",
"test:dist": "node --test \"dist/**/*.test.js\""
},
"dependencies": {
"@maka/core": "0.1.0",
"@modelcontextprotocol/client": "2.0.0"
},
"devDependencies": {
"@modelcontextprotocol/node": "2.0.0",
"@modelcontextprotocol/sdk": "1.30.0",
"@modelcontextprotocol/server": "2.0.0",
"@modelcontextprotocol/server-legacy": "2.0.0"
}
}
@@ -0,0 +1,55 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import { Server } from '@modelcontextprotocol/server';
import { serveStdio } from '@modelcontextprotocol/server/stdio';
import { installStdioFixtureEvents } from './stdio-fixture-events.js';
const record = installStdioFixtureEvents('dual-era');
const factoryDelayMs = Number(process.env.MAKA_MCP_STDIO_FACTORY_DELAY_MS ?? 0);
serveStdio(
async ({ era }) => {
record('factory', { era });
if (era === 'modern' && Number.isFinite(factoryDelayMs) && factoryDelayMs > 0) {
await new Promise((resolve) => setTimeout(resolve, factoryDelayMs));
}
const server = new Server(
{ name: 'maka-dual-era-stdio-fixture', version: '1.0.0' },
{ capabilities: { tools: {} } },
);
server.setRequestHandler('tools/list', async () => ({
tools: [
{
name: 'echo',
description: 'Echo text',
inputSchema: {
type: 'object',
properties: { value: { type: 'string' } },
},
},
],
}));
server.setRequestHandler('tools/call', async ({ params }) => ({
content: [{ type: 'text', text: String(params.arguments?.value ?? '') }],
}));
return server;
},
{ legacy: process.argv.includes('--modern-only') ? 'reject' : 'serve' },
);
@@ -0,0 +1,52 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import { appendFileSync } from 'node:fs';
export function installStdioFixtureEvents(
fixture: string,
): (event: string, details?: Record<string, unknown>) => void {
const path = process.env.MAKA_MCP_STDIO_EVENT_LOG;
if (!path) return () => {};
const record = (event: string, details: Record<string, unknown> = {}) => {
appendFileSync(
path,
`${JSON.stringify({
event,
fixture,
pid: process.pid,
...details,
})}\n`,
'utf8',
);
};
record('start', {
execPath: process.execPath,
argv: process.argv.slice(1),
cwd: process.cwd(),
fixtureEnv: process.env.MAKA_MCP_STDIO_FIXTURE_VALUE ?? null,
});
process.stderr.write(`stdio fixture ${fixture} pid=${process.pid}\n`);
process.once('SIGTERM', () => {
record('signal', { signal: 'SIGTERM' });
process.exit(0);
});
process.once('exit', (code) => record('exit', { code }));
return record;
}
@@ -0,0 +1,227 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import { Server } from '@modelcontextprotocol/sdk/server/index.js';
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
import { CallToolRequestSchema, ListToolsRequestSchema } from '@modelcontextprotocol/sdk/types.js';
import { installStdioFixtureEvents } from './stdio-fixture-events.js';
installStdioFixtureEvents('legacy');
if (process.argv.includes('--crash')) {
process.stderr.write('fixture startup failed: deliberate diagnostic\n');
process.exit(23);
}
if (process.argv.includes('--crash-secret-tail')) {
process.stderr.write('token=sk-live-secret-token-value');
process.exit(24);
}
if (process.argv.includes('--crash-hostile-stderr')) {
process.stderr.write(`${'x'.repeat(1_998)}sk`);
await new Promise((resolve) => setTimeout(resolve, 25));
process.stderr.write('-live-secret-token-value\r\u2028\u206a\n');
process.stderr.write(`${'z'.repeat(10_000)}\n`);
process.stderr.write('after\u2029line\n');
process.stderr.write('sk-live-\u001b12345678\n');
process.stderr.write('AWS_SECRET_ACCESS_KEY\\\n=environment-secret\n');
process.stderr.write('aws configure set aws_secret_access_key \\\ncontinued-secret\n');
process.exit(25);
}
if (process.argv.includes('--crash-many-stderr-lines')) {
process.stderr.write('x\n'.repeat(1_000));
process.exit(26);
}
if (process.argv.includes('--slow-start')) {
await new Promise((resolve) => setTimeout(resolve, 30_000));
}
const server = new Server(
{ name: 'maka-mcp-fixture', version: '1.0.0' },
{ capabilities: { tools: { listChanged: true } } },
);
server.setRequestHandler(ListToolsRequestSchema, async ({ params }) => {
if (process.argv.includes('--schema-annotations')) {
return {
tools: [
{
name: 'annotated',
inputSchema: {
$schema: 'http://json-schema.org/draft-07/schema#',
$comment: 'Generated by the TypeScript SDK schema converter.',
$id: 'https://example.com/annotated.schema.json',
type: 'object' as const,
properties: {
value: {
$schema: 'http://json-schema.org/draft-07/schema#',
type: 'string' as const,
},
},
patternProperties: {
'^tag:': {
$comment: 'Matches tagged string properties.',
type: 'string' as const,
},
},
dependentSchemas: {
value: {
$schema: 'https://json-schema.org/draft/2020-12/schema',
required: ['dependent'],
},
},
dependencies: {
value: {
$schema: 'http://json-schema.org/draft-07/schema#',
required: ['detail'],
},
detail: ['value'],
},
prefixItems: [
{
$comment: 'The first tuple item.',
type: 'string' as const,
},
],
additionalItems: {
$comment: 'Constrain additional tuple items.',
type: 'integer' as const,
},
unevaluatedItems: {
$schema: 'https://json-schema.org/draft/2020-12/schema',
type: 'boolean' as const,
},
contains: {
$schema: 'https://json-schema.org/draft/2020-12/schema',
type: 'number' as const,
},
not: {
$comment: 'Disallow the forbidden property.',
required: ['forbidden'],
},
if: {
$schema: 'https://json-schema.org/draft/2020-12/schema',
required: ['value'],
},
then: {
$comment: 'Require detail when value is present.',
required: ['detail'],
},
else: {
$schema: 'https://json-schema.org/draft/2020-12/schema',
required: ['fallback'],
},
unevaluatedProperties: {
$comment: 'Constrain unevaluated properties.',
type: 'boolean' as const,
},
},
},
],
};
}
if (!params?.cursor) {
return {
tools: [
tool('echo', 'Echo text', true),
tool('rich', 'Return rich content', true),
...(process.argv.includes('--environment')
? [tool('environment', 'Read selected environment variables', true)]
: []),
],
nextCursor: 'page-2',
};
}
if (params.cursor === 'page-2') {
return {
tools: [tool('fail', 'Return MCP isError', false), tool('slow', 'Wait until aborted', false)],
};
}
throw new Error('unexpected cursor');
});
server.setRequestHandler(CallToolRequestSchema, async ({ params }) => {
if (params.name === 'echo') {
return {
content: [{ type: 'text', text: String(params.arguments?.value ?? '') }],
structuredContent: { echoed: params.arguments?.value },
};
}
if (params.name === 'rich') {
return {
content: [
{ type: 'text', text: 'hello' },
{ type: 'image', data: 'aW1hZ2U=', mimeType: 'image/png' },
{ type: 'audio', data: 'YXVkaW8=', mimeType: 'audio/wav' },
{
type: 'resource',
resource: { uri: 'file:///fixture.txt', text: 'resource text', mimeType: 'text/plain' },
},
{
type: 'resource_link',
uri: 'https://example.com/item',
name: 'item',
mimeType: 'text/html',
},
],
};
}
if (params.name === 'fail') {
// With FIXTURE_LEAK_TOKEN set, behaves like a server echoing a secret
// it was handed — the manager must scrub it out of the tool error.
const leak = process.env.FIXTURE_LEAK_TOKEN ? ` ${process.env.FIXTURE_LEAK_TOKEN}` : '';
return { isError: true, content: [{ type: 'text', text: `deliberate failure${leak}` }] };
}
if (params.name === 'slow') {
await new Promise((resolve) => setTimeout(resolve, 30_000));
return { content: [{ type: 'text', text: 'too late' }] };
}
if (params.name === 'environment') {
const names = Array.isArray(params.arguments?.names) ? params.arguments.names : [];
return {
content: [
{
type: 'text',
text: JSON.stringify(
Object.fromEntries(
names
.filter((name): name is string => typeof name === 'string')
.map((name) => [name, process.env[name] ?? null]),
),
),
},
],
};
}
return { isError: true, content: [{ type: 'text', text: 'unknown tool' }] };
});
function tool(name: string, description: string, readOnlyHint: boolean) {
return {
name,
description,
inputSchema: { type: 'object' as const, properties: { value: { type: 'string' } } },
annotations: { readOnlyHint },
};
}
await server.connect(new StdioServerTransport());
if (process.argv.includes('--runtime-stderr')) {
setTimeout(() => process.stderr.write('runtime diagnostic\n'), 500);
}
@@ -0,0 +1,168 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import assert from 'node:assert/strict';
import { describe, test } from 'node:test';
import { McpCredentialCoordinator } from '../credential-coordinator.js';
import type { McpOAuthRecord, McpOAuthStorage } from '../oauth.js';
describe('McpCredentialCoordinator', () => {
test('an abort landing during the storage read blocks the commit', async () => {
// The guard is checked before the read; without the re-check after it,
// an abort arriving while the read waits would still commit the stale
// record — a timed-out OAuth flow persisting its verifier late.
let releaseGet!: () => void;
const gate = new Promise<void>((resolve) => {
releaseGet = resolve;
});
const writes: McpOAuthRecord[] = [];
const storage: McpOAuthStorage = {
get: async () => {
await gate;
return undefined;
},
set: async (_id, record) => {
writes.push(record);
},
delete: async () => {},
};
const coordinator = new McpCredentialCoordinator(storage);
const round = new AbortController();
const flow = coordinator.flowStorage('remote', { signal: round.signal });
const write = flow.set('remote', { codeVerifier: 'late-verifier' });
round.abort();
releaseGet();
await assert.rejects(write, /abandoned/u);
assert.deepEqual(writes, []);
});
test('a stale flow cannot delete or overwrite another writer’s rotation', async () => {
// Process A's flow reads the record, process B rotates it (its own
// coordinator, same backing store), then A's failing flow tries to
// invalidate. Generations match — only the version fence can tell A
// that the material it wants to delete is not the material it read.
const backing = new Map<string, McpOAuthRecord>();
const storage: McpOAuthStorage = {
get: async (id) => backing.get(id) && structuredClone(backing.get(id)),
set: async (id, record) => {
backing.set(id, structuredClone(record));
},
delete: async (id) => {
backing.delete(id);
},
};
await storage.set('remote', { version: 1, tokens: { access_token: 'r1', token_type: 'B' } });
const coordinatorA = new McpCredentialCoordinator(storage);
const coordinatorB = new McpCredentialCoordinator(storage);
const flowA = coordinatorA.flowStorage('remote', {});
await flowA.get('remote'); // A captures version 1
const flowB = coordinatorB.flowStorage('remote', {});
await flowB.get('remote');
await flowB.set('remote', { tokens: { access_token: 'r2-rotated', token_type: 'B' } });
await assert.rejects(flowA.delete('remote'), /rotated by another writer/u);
await assert.rejects(
flowA.set('remote', { tokens: { access_token: 'r1-stale', token_type: 'B' } }),
/rotated by another writer/u,
);
assert.equal(backing.get('remote')?.tokens?.access_token, 'r2-rotated');
});
test('a logout landing during the storage read blocks the commit too', async () => {
let releaseGet!: () => void;
const gate = new Promise<void>((resolve) => {
releaseGet = resolve;
});
let held = true;
const writes: McpOAuthRecord[] = [];
const storage: McpOAuthStorage = {
get: async () => {
if (held) {
held = false;
await gate;
}
return undefined;
},
set: async (_id, record) => {
writes.push(record);
},
delete: async () => {},
};
const coordinator = new McpCredentialCoordinator(storage);
const flow = coordinator.flowStorage('remote', {});
const write = flow.set('remote', { codeVerifier: 'late-verifier' });
const erasing = coordinator.erase('remote');
releaseGet();
await erasing.catch(() => {});
await assert.rejects(write, /cleared/u);
// Only the tombstone landed; the flow's write never did.
assert.equal(writes.length, 1);
assert.equal(writes[0]?.codeVerifier, undefined);
assert.equal(writes[0]?.generation, 1);
});
test('an abandoned erase cannot tombstone the record a newer login stored', async () => {
// A timed-out logout abandons its caller, but the stalled erase keeps
// running. When it resumes it would read the CURRENT record — the fresh
// tokens a newer login just stored — as its basis and tombstone them.
// The abandonment signal fences the commit on both sides of the read.
let releaseGet!: () => void;
const gate = new Promise<void>((resolve) => {
releaseGet = resolve;
});
let stored: McpOAuthRecord = { version: 1, generation: 0 };
const writes: McpOAuthRecord[] = [];
const storage: McpOAuthStorage = {
get: async () => {
await gate;
return stored;
},
set: async (_id, record) => {
writes.push(record);
stored = record;
},
delete: async () => {},
};
const coordinator = new McpCredentialCoordinator(storage);
const round = new AbortController();
const erasing = coordinator.erase('remote', { signal: round.signal });
// The logout round times out while the storage read is still parked;
// a fresh login then completes and rotates the record.
round.abort();
stored = { version: 7, generation: 0 };
releaseGet();
await assert.rejects(erasing, /abandoned/u);
assert.equal(writes.length, 0);
assert.equal(stored.version, 7);
// An already-abandoned erase never reaches storage at all.
const aborted = new AbortController();
aborted.abort();
await assert.rejects(coordinator.erase('remote', { signal: aborted.signal }), /abandoned/u);
assert.equal(writes.length, 0);
});
});
@@ -0,0 +1,49 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import assert from 'node:assert/strict';
import { test } from 'node:test';
import { formatMcpDiagnosticText, MCP_ERROR_DIAGNOSTIC_CODE_POINTS } from '../diagnostic-text.js';
test('fails closed before processing oversized input', () => {
const rendered = formatMcpDiagnosticText('x'.repeat(100_000));
assert.equal(rendered, '[MCP diagnostic omitted: input exceeded limit]');
});
test('redacts a secret that crosses the visible output boundary', () => {
const rendered = formatMcpDiagnosticText(
`${'x'.repeat(78)}sk-live-secret-token-value${'y'.repeat(500)}`,
);
assert.equal([...rendered].length, 80);
assert.doesNotMatch(rendered, /sk-live|secret-token/u);
assert.match(rendered, /\u2026$/u);
});
test('sanitizes control and format characters across the diagnostic boundary', () => {
const rendered = formatMcpDiagnosticText(
'before\r\n\u00ad\u2028\u2029\u206a\u202eafter token=secret-value',
MCP_ERROR_DIAGNOSTIC_CODE_POINTS,
);
assert.doesNotMatch(rendered, /[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/u);
assert.doesNotMatch(rendered, /secret-value/u);
assert.match(rendered, /\[redacted\]/u);
});
@@ -0,0 +1,532 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import assert from 'node:assert/strict';
import { createServer, type IncomingMessage, type ServerResponse } from 'node:http';
import type { Socket } from 'node:net';
import { afterEach, describe, test } from 'node:test';
import { NodeStreamableHTTPServerTransport } from '@modelcontextprotocol/node';
import { Server as McpServer } from '@modelcontextprotocol/server';
import { SSEServerTransport } from '@modelcontextprotocol/server-legacy/sse';
import {
MCP_CONFIG_VERSION,
type McpConfigFile,
type McpProtocolPreference,
type McpToolBinding,
} from '@maka/core/mcp';
import { McpClientManager } from '../index.js';
import { waitFor as pollFor } from '@maka/core/test-only/async-primitives';
const managers: McpClientManager[] = [];
const fixtures: FallbackFixture[] = [];
afterEach(async () => {
await Promise.all(managers.splice(0).map((manager) => manager.close()));
await Promise.all(fixtures.splice(0).map((fixture) => fixture.close()));
});
describe('McpClientManager Streamable HTTP fallback contract', () => {
test('falls back from a pre-handshake 404 or 405 to a real legacy SSE server', async () => {
for (const status of [404, 405] as const) {
const fixture = await createFallbackFixture({ streamable: { kind: 'status', status } });
const manager = createManager();
await manager.sync(remoteConfig(fixture.url, 'auto'));
assert.equal(manager.status('remote')?.state, 'connected');
assert.equal(manager.status('remote')?.transport, 'sse');
assert.deepEqual(manager.status('remote')?.negotiatedProtocol, {
era: 'legacy',
revision: '2025-11-25',
});
assert.equal(fixture.sseGets, 1);
assert.deepEqual(fixture.streamableMethods, ['server/discover', 'initialize']);
assert.ok(fixture.sseMethods.includes('initialize'));
assert.ok(fixture.sseMethods.includes('tools/list'));
assert.deepEqual(
manager.status('remote')?.tools.find((tool) => tool.name === 'echo')?.inputSchema,
{
type: 'object',
properties: {
value: { type: 'string' },
ratio: { type: 'number', 'x-mcp-header': 'Ratio' },
},
},
'legacy discovery must not apply modern x-mcp-header exclusion',
);
assert.deepEqual(
await manager.callTool(bindingFor(manager, 'echo'), { value: `fallback-${status}` }),
{
content: [{ type: 'text', text: `fallback-${status}` }],
structuredContent: undefined,
},
);
await manager.close();
await fixture.close();
}
});
test('does not fall back for non-404/405 HTTP responses', async () => {
const statuses = [400, 401, 403, 408, 409, 415, 429, 500] as const;
for (const status of statuses) {
const fixture = await createFallbackFixture({ streamable: { kind: 'status', status } });
const manager = createManager();
await manager.sync(remoteConfig(fixture.url, 'auto'));
// A 401 is an authorization demand, not a dead transport: the manager
// surfaces needs-auth so the UI can offer a login instead of an error.
// Either way the probe must not fall back to legacy SSE.
const expectedState = status === 401 ? 'needs-auth' : 'error';
assert.equal(manager.status('remote')?.state, expectedState, `HTTP ${status}`);
assert.equal(fixture.streamableMethods[0], 'server/discover', `HTTP ${status}`);
assert.ok(fixture.streamablePosts >= 1, `HTTP ${status}`);
assert.equal(fixture.sseGets, 0, `HTTP ${status}`);
await manager.close();
await fixture.close();
}
});
test('does not fall back from an unexpected successful response body', async () => {
const fixture = await createFallbackFixture({ streamable: { kind: 'unexpected-success' } });
const manager = createManager();
await manager.sync(remoteConfig(fixture.url, 'auto'));
assert.equal(manager.status('remote')?.state, 'error');
assert.equal(fixture.streamablePosts, 1);
assert.equal(fixture.sseGets, 0);
});
test('does not fall back from a network failure', async () => {
const fixture = await createFallbackFixture({ streamable: { kind: 'network-error' } });
const manager = createManager();
await manager.sync(remoteConfig(fixture.url, 'auto'));
assert.equal(manager.status('remote')?.state, 'error');
assert.equal(fixture.streamablePosts, 1);
assert.equal(fixture.sseGets, 0);
});
test('aborts a hanging auto or pinned probe without waiting for the server', async () => {
for (const protocol of ['auto', '2026-07-28'] as const) {
const fixture = await createFallbackFixture({ streamable: { kind: 'hang' } });
const manager = createManager();
const sync = manager.sync(remoteConfig(fixture.url, protocol));
await waitFor(() => fixture.streamablePosts === 1);
assert.equal(manager.cancelConnect('remote'), true);
try {
await settlesWithin(sync);
} finally {
fixture.releaseStreamable();
}
assert.equal(manager.status('remote')?.state, 'disconnected');
assert.equal(fixture.sseGets, 0);
await manager.close();
await fixture.close();
}
});
test('does not start a remote probe after a connecting listener cancels synchronously', async () => {
const fixture = await createFallbackFixture({ streamable: { kind: 'hang' } });
const manager = createManager();
let cancelResult: boolean | undefined;
manager.onChange((status) => {
if (status.serverId === 'remote' && status.state === 'connecting') {
cancelResult = manager.cancelConnect('remote');
}
});
try {
await settlesWithin(manager.sync(remoteConfig(fixture.url, 'auto')));
} finally {
fixture.releaseStreamable();
}
assert.equal(cancelResult, true);
assert.equal(fixture.streamablePosts, 0);
assert.equal(fixture.sseGets, 0);
assert.equal(manager.status('remote')?.state, 'disconnected');
});
test('does not fall back after the Streamable HTTP probe times out', async () => {
const fixture = await createFallbackFixture({ streamable: { kind: 'hang' } });
const manager = createManager(50);
await manager.sync(remoteConfig(fixture.url, 'auto'));
fixture.releaseStreamable();
assert.equal(manager.status('remote')?.state, 'error');
assert.equal(fixture.streamablePosts, 1);
assert.equal(fixture.sseGets, 0);
});
test('does not fall back after legacy initialize succeeded but initialized returned 404 or 405', async () => {
for (const status of [404, 405] as const) {
const fixture = await createFallbackFixture({
streamable: { kind: 'initialized-status', status },
});
const manager = createManager();
await manager.sync(remoteConfig(fixture.url, 'auto'));
assert.equal(manager.status('remote')?.state, 'error', `HTTP ${status}`);
assert.deepEqual(
fixture.streamableMethods.slice(0, 3),
['server/discover', 'initialize', 'notifications/initialized'],
`HTTP ${status}`,
);
assert.equal(fixture.sseGets, 0, `HTTP ${status}`);
await manager.close();
await fixture.close();
}
});
test('an exact modern pin never attempts legacy SSE', async () => {
const fixture = await createFallbackFixture({ streamable: { kind: 'status', status: 404 } });
const manager = createManager();
await manager.sync(remoteConfig(fixture.url, '2026-07-28'));
assert.equal(manager.status('remote')?.state, 'error');
assert.equal(fixture.streamablePosts, 1);
assert.equal(fixture.sseGets, 0);
});
test('an explicit Streamable HTTP transport never attempts legacy SSE', async () => {
const fixture = await createFallbackFixture({ streamable: { kind: 'status', status: 404 } });
const manager = createManager();
await manager.sync(remoteConfig(fixture.url, 'legacy', 'streamable-http'));
assert.equal(manager.status('remote')?.state, 'error');
assert.equal(fixture.streamablePosts, 1);
assert.equal(fixture.sseGets, 0);
});
test('preserves both failures behind one stable public error when SSE also fails', async () => {
for (const status of [404, 405] as const) {
const fixture = await createFallbackFixture({
streamable: { kind: 'status', status },
sse: 'fail',
});
const manager = createManager();
await manager.sync(remoteConfig(fixture.url, 'auto'));
const postsBefore = fixture.streamablePosts;
const getsBefore = fixture.sseGets;
let rejection: unknown;
try {
await manager.connect('remote');
} catch (error) {
rejection = error;
}
assert.ok(rejection instanceof Error);
assert.equal(
rejection.message,
'MCP server "remote" connection failed: Streamable HTTP and legacy SSE connection attempts failed',
);
// The rejection leaves the manager (reconnect → IPC → renderer): its
// cause survives as a SANITIZED copy — the per-transport aggregate
// shape is preserved for diagnosability, but each member is rebuilt
// with a scrubbed message and no deeper chain or payload fields.
const cause = (rejection as Error & { cause?: unknown }).cause;
assert.ok(cause instanceof AggregateError);
assert.equal(cause.errors.length, 2);
for (const member of cause.errors) {
assert.ok(member instanceof Error);
assert.equal((member as Error & { cause?: unknown }).cause, undefined);
}
assert.equal(fixture.streamablePosts, postsBefore + 2);
assert.equal(fixture.sseGets, getsBefore + 1);
await manager.close();
await fixture.close();
}
});
});
function createManager(remoteConnectMs = 5_000): McpClientManager {
const manager = new McpClientManager({
timeouts: { remoteConnectMs, listToolsMs: 5_000, callToolMs: 5_000 },
});
managers.push(manager);
return manager;
}
function remoteConfig(
url: string,
protocol: McpProtocolPreference,
transport: 'auto' | 'streamable-http' = 'auto',
): McpConfigFile {
return {
version: MCP_CONFIG_VERSION,
mcpServers: {
remote: {
url,
transport,
protocol,
},
},
};
}
function bindingFor(manager: McpClientManager, toolName: string): McpToolBinding {
const match = manager
.toolSnapshot()
.tools.find(
({ descriptor }) => descriptor.serverId === 'remote' && descriptor.name === toolName,
);
assert.ok(match, `missing bound MCP tool remote/${toolName}`);
return match.binding;
}
type StreamableBehavior =
| { kind: 'status'; status: number }
| { kind: 'unexpected-success' }
| { kind: 'network-error' }
| { kind: 'hang' }
| { kind: 'initialized-status'; status: 404 | 405 };
interface FallbackFixture {
url: string;
streamablePosts: number;
sseGets: number;
streamableMethods: string[];
sseMethods: string[];
releaseStreamable(): void;
close(): Promise<void>;
}
async function createFallbackFixture(options: {
streamable: StreamableBehavior;
sse?: 'valid' | 'fail';
}): Promise<FallbackFixture> {
let streamablePosts = 0;
let sseGets = 0;
const streamableMethods: string[] = [];
const sseMethods: string[] = [];
let releaseStreamable = () => {};
const streamableRelease = new Promise<void>((resolve) => {
releaseStreamable = resolve;
});
const sockets = new Set<Socket>();
const sseTransports = new Map<string, { transport: SSEServerTransport; server: McpServer }>();
const httpServer = createServer(async (req, res) => {
const url = new URL(req.url ?? '/', 'http://127.0.0.1');
try {
if (url.pathname === '/mcp' && req.method === 'POST') {
streamablePosts += 1;
const body = await readJsonBody(req);
const methods = readProtocolMethods(body);
streamableMethods.push(...methods);
const behavior = options.streamable;
if (behavior.kind === 'network-error') {
req.socket.destroy();
return;
}
if (behavior.kind === 'hang') {
await streamableRelease;
writeHttpFailure(res, 404);
return;
}
if (behavior.kind === 'unexpected-success') {
res
.writeHead(200, { 'content-type': 'text/html; charset=utf-8' })
.end('<!doctype html><title>not MCP</title>');
return;
}
if (behavior.kind === 'status') {
writeHttpFailure(res, behavior.status);
return;
}
if (methods.includes('notifications/initialized')) {
writeHttpFailure(res, behavior.status);
return;
}
await handleLegacyStreamableRequest(req, res, body);
return;
}
if (url.pathname === '/mcp' && req.method === 'GET') {
sseGets += 1;
if (options.sse === 'fail') {
res.writeHead(503, { 'content-type': 'text/plain; charset=utf-8' }).end('unavailable');
return;
}
const transport = new SSEServerTransport('/messages', res);
const server = createLegacyServer();
sseTransports.set(transport.sessionId, { transport, server });
res.once('close', () => sseTransports.delete(transport.sessionId));
await server.connect(transport);
return;
}
if (url.pathname === '/messages' && req.method === 'POST') {
const body = await readJsonBody(req);
sseMethods.push(...readProtocolMethods(body));
const entry = sseTransports.get(url.searchParams.get('sessionId') ?? '');
if (!entry) {
res.writeHead(400).end('unknown SSE session');
return;
}
await entry.transport.handlePostMessage(req, res, body);
return;
}
res.writeHead(404).end('not found');
} catch (error) {
if (!res.headersSent) res.writeHead(500);
res.end(error instanceof Error ? error.message : String(error));
}
});
httpServer.on('connection', (socket) => {
sockets.add(socket);
socket.once('close', () => sockets.delete(socket));
});
await new Promise<void>((resolve, reject) => {
httpServer.once('error', reject);
httpServer.listen(0, '127.0.0.1', resolve);
});
const address = httpServer.address();
if (!address || typeof address === 'string') throw new Error('fallback fixture did not bind TCP');
let closed = false;
const fixture: FallbackFixture = {
url: `http://127.0.0.1:${address.port}/mcp`,
get streamablePosts() {
return streamablePosts;
},
get sseGets() {
return sseGets;
},
streamableMethods,
sseMethods,
releaseStreamable,
close: async () => {
if (closed) return;
closed = true;
await Promise.all(
[...sseTransports.values()].map(async ({ transport, server }) => {
await transport.close().catch(() => {});
await server.close().catch(() => {});
}),
);
for (const socket of sockets) socket.destroy();
await new Promise<void>((resolve, reject) =>
httpServer.close((error) => (error ? reject(error) : resolve())),
);
},
};
fixtures.push(fixture);
return fixture;
}
async function handleLegacyStreamableRequest(
req: IncomingMessage,
res: ServerResponse,
body: unknown,
): Promise<void> {
const transport = new NodeStreamableHTTPServerTransport({ sessionIdGenerator: undefined });
const server = createLegacyServer();
await server.connect(transport);
res.once('close', () => {
void transport.close();
void server.close();
});
await transport.handleRequest(req, res, body);
}
function createLegacyServer(): McpServer {
const server = new McpServer(
{ name: 'maka-fallback-fixture', version: '1.0.0' },
{ capabilities: { tools: {} } },
);
server.setRequestHandler('tools/list', async () => ({
tools: [
{
name: 'echo',
description: 'Echo text',
inputSchema: {
type: 'object',
properties: {
value: { type: 'string' },
ratio: { type: 'number', 'x-mcp-header': 'Ratio' },
},
},
},
],
}));
server.setRequestHandler('tools/call', async ({ params }) => ({
content: [{ type: 'text', text: String(params.arguments?.value ?? '') }],
}));
return server;
}
function writeHttpFailure(res: ServerResponse, status: number): void {
res
.writeHead(status, { 'content-type': 'application/json; charset=utf-8' })
.end(JSON.stringify({ error: `HTTP ${status}` }));
}
function readProtocolMethods(body: unknown): string[] {
return (Array.isArray(body) ? body : [body]).flatMap((message) => {
if (
typeof message === 'object' &&
message !== null &&
'method' in message &&
typeof message.method === 'string'
) {
return [message.method];
}
return [];
});
}
async function readJsonBody(req: IncomingMessage): Promise<unknown> {
const chunks: Buffer[] = [];
for await (const chunk of req) chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
const text = Buffer.concat(chunks).toString('utf8');
return text ? JSON.parse(text) : undefined;
}
async function waitFor(predicate: () => boolean, timeoutMs = 1_000): Promise<void> {
await pollFor(predicate, { timeoutMs, pollMs: 5, message: 'condition was not reached' });
}
async function settlesWithin<T>(promise: Promise<T>, timeoutMs = 500): Promise<T> {
let timer: ReturnType<typeof setTimeout> | undefined;
try {
return await Promise.race([
promise,
new Promise<never>((_resolve, reject) => {
timer = setTimeout(
() => reject(new Error('operation did not settle after abort')),
timeoutMs,
);
}),
]);
} finally {
if (timer) clearTimeout(timer);
}
}
@@ -0,0 +1,534 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import assert from 'node:assert/strict';
import { createServer, type IncomingMessage, type ServerResponse } from 'node:http';
import { afterEach, describe, test } from 'node:test';
import { toNodeHandler } from '@modelcontextprotocol/node';
import { createMcpHandler, InMemoryServerEventBus, Server } from '@modelcontextprotocol/server';
import { MCP_CONFIG_VERSION, type McpConfigFile, type McpServerStatus } from '@maka/core/mcp';
import { McpClientManager } from '../index.js';
import { waitFor as pollFor } from '@maka/core/test-only/async-primitives';
const managers: McpClientManager[] = [];
const fixtures: SubscriptionFixture[] = [];
afterEach(async () => {
await Promise.all(managers.splice(0).map((manager) => manager.close()));
await Promise.all(fixtures.splice(0).map((fixture) => fixture.close()));
});
describe('McpClientManager modern tool-list subscriptions', () => {
test('coalesces an honored notification burst into one bounded trailing refresh', async () => {
const fixture = await createSubscriptionFixture();
const manager = createManager();
const connectedSnapshots: string[][] = [];
manager.onChange((status) => {
if (status.state === 'connected') connectedSnapshots.push(toolNames(status));
});
await manager.sync(modernConfig(fixture.url));
fixture.setTools(['middle']);
const gate = fixture.blockNextToolList();
fixture.notifyToolsChanged();
await gate.entered;
fixture.setTools(['final']);
for (let index = 0; index < 20; index += 1) fixture.notifyToolsChanged();
await settleEventLoop();
gate.release();
await waitFor(
() => fixture.toolListCalls === 3 && toolNames(manager.status('remote'))[0] === 'final',
);
assert.equal(fixture.toolListCalls, 3);
assert.deepEqual(connectedSnapshots, [['initial'], ['final']]);
assert.equal(manager.status('remote')?.error, undefined);
});
test('coalesces a change received during initial discovery before publishing connected state', async () => {
const fixture = await createSubscriptionFixture();
const initialList = fixture.blockNextToolList();
const manager = createManager();
const connectedSnapshots: string[][] = [];
manager.onChange((status) => {
if (status.state === 'connected') connectedSnapshots.push(toolNames(status));
});
const syncing = manager.sync(modernConfig(fixture.url));
await initialList.entered;
await waitFor(() => fixture.subscriptionListeners === 1);
fixture.setTools(['changed-during-connect']);
fixture.notifyToolsChanged();
await settleEventLoop();
initialList.release();
await syncing;
assert.equal(fixture.toolListCalls, 2);
assert.deepEqual(connectedSnapshots, [['changed-during-connect']]);
assert.deepEqual(toolNames(manager.status('remote')), ['changed-during-connect']);
});
for (const mode of ['missing', 'unhonored', 'rejected'] as const) {
test(`keeps the connection usable when the subscription acknowledgement is ${mode}`, async () => {
const fixture = await createSubscriptionFixture({ subscriptionMode: mode });
const manager = createManager(mode === 'missing' ? 150 : 2_000);
await manager.sync(modernConfig(fixture.url));
const status = manager.status('remote');
assert.equal(status?.state, 'connected');
assert.deepEqual(status?.negotiatedProtocol, {
era: 'modern',
revision: '2026-07-28',
});
assert.deepEqual(toolNames(status), ['initial']);
assert.deepEqual(
manager.toolSnapshot().tools.map(({ descriptor }) => descriptor.name),
['initial'],
);
assert.match(status?.error ?? '', /tool-list subscription/u);
if (mode === 'unhonored') {
assert.match(status?.error ?? '', /did not honor/u);
} else {
assert.match(status?.error ?? '', /unavailable/u);
}
});
}
test('does not wait for an unhonored subscription cancellation response during setup', async () => {
const fixture = await createSubscriptionFixture({
subscriptionMode: 'unhonored',
hangCancellation: true,
});
const manager = createManager();
try {
await settlesWithin(manager.sync(modernConfig(fixture.url)));
} finally {
fixture.releaseCancellation();
}
assert.equal(manager.status('remote')?.state, 'connected');
assert.match(manager.status('remote')?.error ?? '', /did not honor/u);
});
for (const operation of ['disconnect', 'close'] as const) {
test(`${operation} aborts an unanswered subscription cancellation request`, async () => {
const fixture = await createSubscriptionFixture({ hangCancellation: true });
const manager = createManager();
await manager.sync(modernConfig(fixture.url));
try {
await settlesWithin(
operation === 'disconnect' ? manager.disconnect('remote') : manager.close(),
);
} finally {
fixture.releaseCancellation();
}
if (operation === 'disconnect') {
assert.equal(manager.status('remote')?.state, 'disconnected');
}
});
}
test('does not attribute a normal tool transport failure to the subscription', async () => {
const fixture = await createSubscriptionFixture();
const manager = createManager();
await manager.sync(modernConfig(fixture.url));
const tool = manager.toolSnapshot().tools[0];
assert.ok(tool);
fixture.failToolCalls(true);
await assert.rejects(manager.callTool(tool.binding, {}));
assert.equal(manager.status('remote')?.state, 'connected');
assert.equal(manager.status('remote')?.error, undefined);
assert.equal(fixture.subscriptionListeners, 1);
fixture.failToolCalls(false);
assert.deepEqual(await manager.callTool(tool.binding, {}), {
content: [{ type: 'text', text: 'ok' }],
structuredContent: undefined,
});
assert.equal(manager.status('remote')?.error, undefined);
});
test('keeps subscription and refresh diagnostics in separate lifecycle slots', async () => {
const fixture = await createSubscriptionFixture();
const manager = createManager();
await manager.sync(modernConfig(fixture.url));
const original = manager.toolSnapshot().tools[0];
assert.ok(original);
const snapshotBeforeFailure = manager.toolSnapshot();
let refreshDiagnosticUpdates = 0;
const unsubscribe = manager.onChange((status) => {
if (/tool refresh failed/u.test(status.error ?? '')) refreshDiagnosticUpdates += 1;
});
fixture.failToolLists(true);
fixture.notifyToolsChanged();
await waitFor(() => /tool refresh failed/u.test(manager.status('remote')?.error ?? ''));
await settleEventLoop();
assert.equal(refreshDiagnosticUpdates, 1);
assert.strictEqual(manager.toolSnapshot(), snapshotBeforeFailure);
unsubscribe();
fixture.failToolLists(false);
await fixture.rotateHandler();
await waitFor(() =>
/tool-list subscription closed (?:graceful|remote)/u.test(
manager.status('remote')?.error ?? '',
),
);
const degraded = manager.status('remote');
assert.equal(degraded?.state, 'connected');
assert.deepEqual(degraded?.negotiatedProtocol, {
era: 'modern',
revision: '2026-07-28',
});
assert.deepEqual(toolNames(degraded), ['initial']);
assert.equal(manager.toolSnapshot().tools[0]?.binding, original.binding);
assert.match(degraded?.error ?? '', /tool refresh failed/u);
assert.match(degraded?.error ?? '', /tool-list subscription closed/u);
fixture.setTools(['after-recovery']);
await manager.refreshTools('remote');
const refreshed = manager.status('remote');
assert.deepEqual(toolNames(refreshed), ['after-recovery']);
assert.doesNotMatch(refreshed?.error ?? '', /tool refresh failed/u);
assert.match(refreshed?.error ?? '', /tool-list subscription closed/u);
await manager.reconnect('remote');
const reconnected = manager.status('remote');
assert.equal(reconnected?.state, 'connected');
assert.deepEqual(toolNames(reconnected), ['after-recovery']);
assert.deepEqual(reconnected?.negotiatedProtocol, {
era: 'modern',
revision: '2026-07-28',
});
assert.equal(reconnected?.error, undefined);
});
});
function createManager(remoteConnectMs = 2_000): McpClientManager {
const manager = new McpClientManager({
timeouts: { remoteConnectMs, listToolsMs: 2_000, callToolMs: 2_000 },
});
managers.push(manager);
return manager;
}
function modernConfig(url: string): McpConfigFile {
return {
version: MCP_CONFIG_VERSION,
mcpServers: {
remote: {
url,
transport: 'streamable-http',
protocol: 'auto',
},
},
};
}
function toolNames(status: McpServerStatus | undefined): string[] {
return status?.tools.map((tool) => tool.name) ?? [];
}
type SubscriptionMode = 'honored' | 'missing' | 'unhonored' | 'rejected';
interface ToolListGate {
entered: Promise<void>;
release(): void;
}
interface SubscriptionFixture {
readonly url: string;
readonly toolListCalls: number;
readonly subscriptionListeners: number;
setTools(names: string[]): void;
failToolLists(value: boolean): void;
failToolCalls(value: boolean): void;
blockNextToolList(): ToolListGate;
notifyToolsChanged(): void;
rotateHandler(): Promise<void>;
releaseCancellation(): void;
close(): Promise<void>;
}
async function createSubscriptionFixture(
options: { subscriptionMode?: SubscriptionMode; hangCancellation?: boolean } = {},
): Promise<SubscriptionFixture> {
const subscriptionMode = options.subscriptionMode ?? 'honored';
let tools = ['initial'];
let shouldFailToolLists = false;
let shouldFailToolCalls = false;
let toolListCalls = 0;
let nextToolListGate: InternalGate | undefined;
const toolListGates = new Set<InternalGate>();
const rawSubscriptions = new Set<ServerResponse>();
const handlers = new Set<ReturnType<typeof createMcpHandler>>();
let releaseCancellation = () => {};
const cancellationRelease = new Promise<void>((resolve) => {
releaseCancellation = resolve;
});
const createHandlerGeneration = () => {
const bus = new InMemoryServerEventBus();
const handler = createMcpHandler(
() => {
const server = new Server(
{ name: 'maka-subscription-fixture', version: '1.0.0' },
{ capabilities: { tools: { listChanged: true } } },
);
server.setRequestHandler('tools/list', async () => {
toolListCalls += 1;
const result = tools.map((name) => ({
name,
inputSchema: { type: 'object' as const },
}));
const gate = nextToolListGate;
nextToolListGate = undefined;
if (gate) {
gate.markEntered();
try {
await gate.wait;
} finally {
toolListGates.delete(gate);
}
}
if (shouldFailToolLists) throw new Error('fixture tool list failed');
return { tools: result };
});
server.setRequestHandler('tools/call', async () => ({
content: [{ type: 'text', text: 'ok' }],
}));
return server;
},
{
legacy: 'reject',
keepAliveMs: 0,
bus,
...(subscriptionMode === 'rejected' ? { maxSubscriptions: 0 } : {}),
},
);
handlers.add(handler);
return { bus, handler, nodeHandler: toNodeHandler(handler) };
};
let current = createHandlerGeneration();
const httpServer = createServer(async (req, res) => {
try {
if (new URL(req.url ?? '/', 'http://127.0.0.1').pathname !== '/mcp') {
res.writeHead(404).end('not found');
return;
}
const body = await readJsonBody(req);
const method = requestMethod(body);
if (options.hangCancellation && method === 'notifications/cancelled') {
await cancellationRelease;
res.writeHead(204).end();
return;
}
if (shouldFailToolCalls && method === 'tools/call') {
res
.writeHead(500, { 'content-type': 'text/plain; charset=utf-8' })
.end('tool failed upstream');
return;
}
if (
(subscriptionMode === 'missing' || subscriptionMode === 'unhonored') &&
method === 'subscriptions/listen'
) {
serveRawSubscription(res, body, subscriptionMode, rawSubscriptions);
return;
}
await current.nodeHandler(req, res, body);
} catch (error) {
if (!res.headersSent) res.writeHead(500);
res.end(error instanceof Error ? error.message : String(error));
}
});
await new Promise<void>((resolve, reject) => {
httpServer.once('error', reject);
httpServer.listen(0, '127.0.0.1', resolve);
});
const address = httpServer.address();
if (!address || typeof address === 'string') throw new Error('subscription fixture did not bind');
const fixture: SubscriptionFixture = {
url: `http://127.0.0.1:${address.port}/mcp`,
get toolListCalls() {
return toolListCalls;
},
get subscriptionListeners() {
return current.bus.listenerCount;
},
setTools(names) {
tools = [...names];
},
failToolLists(value) {
shouldFailToolLists = value;
},
failToolCalls(value) {
shouldFailToolCalls = value;
},
blockNextToolList() {
if (nextToolListGate) throw new Error('a tool-list gate is already pending');
const gate = createGate();
toolListGates.add(gate);
nextToolListGate = gate;
return { entered: gate.entered, release: gate.release };
},
notifyToolsChanged() {
current.handler.notify.toolsChanged();
},
async rotateHandler() {
const previous = current;
current = createHandlerGeneration();
await previous.handler.close();
},
releaseCancellation,
async close() {
releaseCancellation();
for (const gate of toolListGates) gate.release();
toolListGates.clear();
for (const response of rawSubscriptions) response.end();
rawSubscriptions.clear();
await Promise.all([...handlers].map((handler) => handler.close()));
const closed = new Promise<void>((resolve, reject) =>
httpServer.close((error) => (error ? reject(error) : resolve())),
);
httpServer.closeAllConnections();
await closed;
},
};
fixtures.push(fixture);
return fixture;
}
interface InternalGate {
entered: Promise<void>;
wait: Promise<void>;
markEntered(): void;
release(): void;
}
function createGate(): InternalGate {
let markEntered = () => {};
let release = () => {};
const entered = new Promise<void>((resolve) => {
markEntered = resolve;
});
const wait = new Promise<void>((resolve) => {
release = resolve;
});
return { entered, wait, markEntered, release };
}
function serveRawSubscription(
response: ServerResponse,
body: unknown,
mode: 'missing' | 'unhonored',
open: Set<ServerResponse>,
): void {
response.writeHead(200, {
'content-type': 'text/event-stream',
'cache-control': 'no-cache, no-transform',
connection: 'keep-alive',
});
open.add(response);
response.once('close', () => open.delete(response));
if (mode === 'missing') {
response.write(': acknowledgement intentionally withheld\n\n');
return;
}
const id = requestId(body);
response.write(
`event: message\ndata: ${JSON.stringify({
jsonrpc: '2.0',
method: 'notifications/subscriptions/acknowledged',
params: {
notifications: {},
_meta: { 'io.modelcontextprotocol/subscriptionId': id },
},
})}\n\n`,
);
}
function requestMethod(body: unknown): string | undefined {
if (typeof body !== 'object' || body === null || !('method' in body)) return undefined;
return typeof body.method === 'string' ? body.method : undefined;
}
function requestId(body: unknown): string | number {
if (typeof body !== 'object' || body === null || !('id' in body)) {
throw new Error('subscription request did not include an id');
}
if (typeof body.id !== 'string' && typeof body.id !== 'number') {
throw new Error('subscription request had an invalid id');
}
return body.id;
}
async function readJsonBody(req: IncomingMessage): Promise<unknown> {
const chunks: Buffer[] = [];
for await (const chunk of req) chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
const text = Buffer.concat(chunks).toString('utf8');
return text ? JSON.parse(text) : undefined;
}
async function waitFor(predicate: () => boolean, timeoutMs = 2_000): Promise<void> {
await pollFor(predicate, {
timeoutMs,
pollMs: 5,
message: 'condition was not met before timeout',
});
}
async function settleEventLoop(): Promise<void> {
for (let index = 0; index < 4; index += 1) {
await new Promise<void>((resolve) => setImmediate(resolve));
}
await new Promise((resolve) => setTimeout(resolve, 150));
}
async function settlesWithin<T>(promise: Promise<T>, timeoutMs = 500): Promise<T> {
let timer: ReturnType<typeof setTimeout> | undefined;
try {
return await Promise.race([
promise,
new Promise<never>((_resolve, reject) => {
timer = setTimeout(
() => reject(new Error('subscription lifecycle did not settle')),
timeoutMs,
);
}),
]);
} finally {
if (timer) clearTimeout(timer);
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,417 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import assert from 'node:assert/strict';
import { createServer, type IncomingMessage } from 'node:http';
import { afterEach, describe, test } from 'node:test';
import { SdkError, SdkErrorCode, type Tool } from '@modelcontextprotocol/client';
import { toNodeHandler } from '@modelcontextprotocol/node';
import { createMcpHandler, inputRequired, Server } from '@modelcontextprotocol/server';
import {
MCP_CONFIG_VERSION,
type McpConfigFile,
type McpProtocolPreference,
type McpToolBinding,
} from '@maka/core/mcp';
import { McpClientManager, McpToolCallError } from '../index.js';
const managers: McpClientManager[] = [];
const fixtures: ModernRemoteFixture[] = [];
const HOSTILE_HEADER_PATH = `token=sk-live-secret-token-value\r\n${'x'.repeat(1_000)}`;
afterEach(async () => {
await Promise.all(managers.splice(0).map((manager) => manager.close()));
await Promise.all(fixtures.splice(0).map((fixture) => fixture.close()));
});
describe('McpClientManager modern Streamable HTTP E2E', () => {
test('auto negotiates 2026-07-28 and clears live protocol status on disconnect', async () => {
const fixture = await createModernRemoteFixture();
const manager = createManager();
await manager.sync(modernConfig(fixture.url, 'auto'));
assert.equal(fixture.protocolMethods[0], 'server/discover');
assert.deepEqual(manager.status('remote')?.negotiatedProtocol, {
era: 'modern',
revision: '2026-07-28',
});
assert.equal(manager.status('remote')?.transport, 'streamable-http');
assert.deepEqual(
manager.status('remote')?.tools.map((tool) => tool.name),
['echo', 'structured', 'needs-input'],
);
await manager.disconnect('remote');
assert.equal(manager.status('remote')?.state, 'disconnected');
assert.equal(manager.status('remote')?.negotiatedProtocol, undefined);
assert.deepEqual(manager.status('remote')?.tools, []);
});
test('pins the exact 2026-07-28 revision', async () => {
const fixture = await createModernRemoteFixture();
const manager = createManager();
await manager.sync(modernConfig(fixture.url, '2026-07-28'));
assert.deepEqual(manager.status('remote')?.negotiatedProtocol, {
era: 'modern',
revision: '2026-07-28',
});
assert.equal(fixture.protocolMethods[0], 'server/discover');
});
test('does not issue tools/list when a modern server omits the tools capability', async () => {
const fixture = await createModernRemoteFixture({ advertiseTools: false });
let now = 1;
const manager = createManager({ now: () => now });
await manager.sync(modernConfig(fixture.url, 'auto'));
assert.deepEqual(manager.status('remote')?.negotiatedProtocol, {
era: 'modern',
revision: '2026-07-28',
});
assert.equal(manager.status('remote')?.toolCount, 0);
assert.deepEqual(manager.toolSnapshot().tools, []);
assert.equal(fixture.protocolMethods.includes('tools/list'), false);
now = 2;
assert.deepEqual(await manager.refreshTools('remote'), []);
assert.equal(manager.status('remote')?.updatedAt, 2);
now = 3;
assert.deepEqual(await manager.refreshTools('remote'), []);
assert.equal(manager.status('remote')?.updatedAt, 3);
assert.equal(fixture.protocolMethods.includes('tools/list'), false);
});
test('preserves every modern structuredContent JSON shape', async () => {
const fixture = await createModernRemoteFixture();
const manager = createManager();
await manager.sync(modernConfig(fixture.url, 'auto'));
const binding = bindingFor(manager, 'structured');
const cases = [
['object', { ok: true }],
['array', [1, 'two']],
['scalar', 'ready'],
['null', null],
] as const;
for (const [kind, expected] of cases) {
const result = await manager.callTool(binding, { kind });
assert.deepEqual(result.structuredContent, expected);
assert.deepEqual(result.content, [{ type: 'text', text: kind }]);
}
});
test('surfaces input_required without silently retrying the tool', async () => {
const fixture = await createModernRemoteFixture();
const manager = createManager();
await manager.sync(modernConfig(fixture.url, 'auto'));
await assert.rejects(
manager.callTool(bindingFor(manager, 'needs-input'), {}),
(error: unknown) =>
error instanceof McpToolCallError &&
error.serverId === 'remote' &&
error.toolName === 'needs-input' &&
SdkError.isInstance(error.cause) &&
error.cause.code === SdkErrorCode.UnsupportedResultType &&
/unsupported deferred tool result/u.test(error.message),
);
assert.equal(fixture.toolCalls.get('needs-input'), 1);
assert.equal(fixture.protocolMethods.filter((method) => method === 'tools/call').length, 1);
});
test('partitions SEP-2243 definitions and mirrors safe arguments on the wire', async () => {
const fixture = await createModernRemoteFixture({ includeHeaderTools: true });
const manager = createManager();
await manager.sync(modernConfig(fixture.url, 'auto'));
assert.deepEqual(
manager
.toolSnapshot()
.tools.map(({ descriptor }) => descriptor.name)
.sort(),
['echo', 'header-echo', 'needs-input', 'structured'],
);
assert.equal(bindingForOptional(manager, 'invalid-header'), undefined);
const binding = bindingFor(manager, 'header-echo');
assert.deepEqual(await manager.callTool(binding, { shard: 42, value: 'safe' }), {
content: [{ type: 'text', text: 'safe' }],
structuredContent: undefined,
});
assert.equal(fixture.toolCallHeaders.get('header-echo'), '42');
assert.equal(fixture.toolCalls.get('header-echo'), 1);
const methodsBeforeUnsafeCall = fixture.protocolMethods.length;
await assert.rejects(
manager.callTool(binding, { shard: Number.MAX_SAFE_INTEGER + 1, value: 'unsafe' }),
(error: unknown) =>
error instanceof McpToolCallError &&
error.serverId === 'remote' &&
error.toolName === 'header-echo' &&
/unsafe integer argument at shard/u.test(error.message),
);
await assert.rejects(
manager.callTool(binding, { [HOSTILE_HEADER_PATH]: Number.MAX_SAFE_INTEGER + 1 }),
(error: unknown) =>
error instanceof McpToolCallError &&
error.message.length <= 600 &&
!/[\r\n]|sk-live|secret-token/u.test(error.message),
);
assert.equal(fixture.protocolMethods.length, methodsBeforeUnsafeCall);
assert.equal(fixture.toolCalls.get('header-echo'), 1);
});
});
function createManager(options: { now?: () => number } = {}): McpClientManager {
const manager = new McpClientManager({
...options,
timeouts: { remoteConnectMs: 5_000, listToolsMs: 5_000, callToolMs: 5_000 },
});
managers.push(manager);
return manager;
}
function bindingFor(manager: McpClientManager, toolName: string): McpToolBinding {
const binding = bindingForOptional(manager, toolName);
assert.ok(binding, `missing bound MCP tool remote/${toolName}`);
return binding;
}
function bindingForOptional(
manager: McpClientManager,
toolName: string,
): McpToolBinding | undefined {
return manager
.toolSnapshot()
.tools.find(
({ descriptor }) => descriptor.serverId === 'remote' && descriptor.name === toolName,
)?.binding;
}
function modernConfig(url: string, protocol: McpProtocolPreference): McpConfigFile {
return {
version: MCP_CONFIG_VERSION,
mcpServers: {
remote: {
url,
transport: 'streamable-http',
protocol,
},
},
};
}
interface ModernRemoteFixture {
url: string;
protocolMethods: string[];
toolCalls: Map<string, number>;
toolCallHeaders: Map<string, string | undefined>;
close(): Promise<void>;
}
async function createModernRemoteFixture(
options: { advertiseTools?: boolean; includeHeaderTools?: boolean } = {},
): Promise<ModernRemoteFixture> {
const advertiseTools = options.advertiseTools !== false;
const protocolMethods: string[] = [];
const toolCalls = new Map<string, number>();
const toolCallHeaders = new Map<string, string | undefined>();
const errors: Error[] = [];
const handler = createMcpHandler(
() => {
const server = new Server(
{ name: 'maka-modern-fixture', version: '1.0.0' },
{ capabilities: advertiseTools ? { tools: {} } : {} },
);
if (advertiseTools) {
server.setRequestHandler('tools/list', async () => {
const tools: Tool[] = [
modernTool('echo'),
modernTool('structured', {}),
modernTool('needs-input'),
];
if (options.includeHeaderTools) {
tools.push(
{
name: 'header-echo',
inputSchema: {
type: 'object',
properties: {
shard: { type: 'integer', 'x-mcp-header': 'Shard' },
value: { type: 'string' },
[HOSTILE_HEADER_PATH]: { type: 'integer', 'x-mcp-header': 'Hostile' },
},
},
},
{
name: 'invalid-header',
inputSchema: {
type: 'object',
properties: {
ratio: { type: 'number', 'x-mcp-header': 'Ratio' },
},
},
},
);
}
return { tools };
});
server.setRequestHandler('tools/call', async ({ params }) => {
toolCalls.set(params.name, (toolCalls.get(params.name) ?? 0) + 1);
const args = params.arguments ?? {};
if (params.name === 'needs-input') {
return inputRequired({ requestState: 'awaiting-confirmation' });
}
if (params.name === 'structured') {
const kind = args.kind;
return {
content: [{ type: 'text', text: String(kind) }],
structuredContent:
kind === 'object'
? { ok: true }
: kind === 'array'
? [1, 'two']
: kind === 'scalar'
? 'ready'
: null,
};
}
return {
content: [{ type: 'text', text: String(args.value ?? '') }],
};
});
}
return server;
},
{
legacy: 'reject',
keepAliveMs: 0,
onerror: (error) => errors.push(error),
},
);
const nodeHandler = toNodeHandler(handler, { onerror: (error) => errors.push(error) });
const httpServer = createServer(async (req, res) => {
try {
if (new URL(req.url ?? '/', 'http://127.0.0.1').pathname !== '/mcp') {
res.writeHead(404).end('not found');
return;
}
const body = await readJsonBody(req);
const methods = readProtocolMethods(body);
protocolMethods.push(...methods);
for (const toolName of readToolCallNames(body)) {
toolCallHeaders.set(toolName, headerValue(req, 'mcp-param-shard'));
}
await nodeHandler(req, res, body);
} catch (error) {
errors.push(error instanceof Error ? error : new Error(String(error)));
if (!res.headersSent) res.writeHead(500);
res.end('modern fixture failed');
}
});
await new Promise<void>((resolve, reject) => {
httpServer.once('error', reject);
httpServer.listen(0, '127.0.0.1', resolve);
});
const address = httpServer.address();
if (!address || typeof address === 'string') throw new Error('modern fixture did not bind TCP');
const fixture: ModernRemoteFixture = {
url: `http://127.0.0.1:${address.port}/mcp`,
protocolMethods,
toolCalls,
toolCallHeaders,
close: async () => {
await handler.close();
await new Promise<void>((resolve, reject) =>
httpServer.close((error) => (error ? reject(error) : resolve())),
);
assert.deepEqual(errors, []);
},
};
fixtures.push(fixture);
return fixture;
}
function modernTool(name: string, outputSchema?: Record<string, unknown>): Tool {
return {
name,
inputSchema:
name === 'structured'
? {
type: 'object' as const,
properties: {
kind: { enum: ['object', 'array', 'scalar', 'null'] },
},
required: ['kind'],
}
: { type: 'object' as const },
...(outputSchema === undefined ? {} : { outputSchema }),
};
}
function readProtocolMethods(body: unknown): string[] {
return (Array.isArray(body) ? body : [body]).flatMap((message) => {
if (
typeof message === 'object' &&
message !== null &&
'method' in message &&
typeof message.method === 'string'
) {
return [message.method];
}
return [];
});
}
function readToolCallNames(body: unknown): string[] {
return (Array.isArray(body) ? body : [body]).flatMap((message) => {
if (
typeof message === 'object' &&
message !== null &&
'method' in message &&
message.method === 'tools/call' &&
'params' in message &&
typeof message.params === 'object' &&
message.params !== null &&
'name' in message.params &&
typeof message.params.name === 'string'
) {
return [message.params.name];
}
return [];
});
}
function headerValue(req: IncomingMessage, name: string): string | undefined {
const value = req.headers[name];
return Array.isArray(value) ? value.join(', ') : value;
}
async function readJsonBody(req: IncomingMessage): Promise<unknown> {
const chunks: Buffer[] = [];
for await (const chunk of req) chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
const text = Buffer.concat(chunks).toString('utf8');
return text ? JSON.parse(text) : undefined;
}
File diff suppressed because it is too large. Load diff
+283
View File
@@ -0,0 +1,283 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import assert from 'node:assert/strict';
import { describe, test } from 'node:test';
import {
formatMcpHeaderExclusionWarning,
MCP_HEADER_WARNING_LENGTH_LIMIT,
partitionMcpHeaderToolDefinitions,
validateMcpHeaderArguments,
validateMcpHeaderDefinition,
type McpHeaderToolRejection,
} from '../sep-2243.js';
describe('SEP-2243 definition validation', () => {
test('collects nested string, integer, and boolean properties', () => {
const result = validateMcpHeaderDefinition({
type: 'object',
properties: {
region: { type: 'string', 'x-mcp-header': 'Region' },
options: {
type: 'object',
properties: {
attempt: { type: 'integer', 'x-mcp-header': 'Attempt' },
dryRun: { type: 'boolean', 'x-mcp-header': 'Dry-Run' },
},
},
},
});
assert.equal(result.valid, true);
if (!result.valid) return;
assert.deepEqual(result.declarations, [
{ path: ['region'], headerName: 'Region', type: 'string' },
{ path: ['options', 'attempt'], headerName: 'Attempt', type: 'integer' },
{ path: ['options', 'dryRun'], headerName: 'Dry-Run', type: 'boolean' },
]);
});
test('rejects number even though the pinned SDK accepts it', () => {
assertInvalid(
{
type: 'object',
properties: {
ratio: { type: 'number', 'x-mcp-header': 'Ratio' },
},
},
'property_type_unsupported',
['ratio'],
);
});
test('uses stable codes for malformed annotation values and property types', () => {
assertInvalid(schemaFor({ type: 'string', 'x-mcp-header': 42 }), 'annotation_not_string', [
'value',
]);
assertInvalid(schemaFor({ type: 'string', 'x-mcp-header': '' }), 'header_name_empty', [
'value',
]);
assertInvalid(
schemaFor({ type: ['string', 'null'], 'x-mcp-header': 'Value' }),
'property_type_unsupported',
['value'],
);
});
test('requires an RFC 9110 token for the header name', () => {
for (const headerName of ['My Region', 'Region:Primary', 'Région', 'Region\t1']) {
assertInvalid(
schemaFor({ type: 'string', 'x-mcp-header': headerName }),
'header_name_invalid',
['value'],
);
}
const allowed = validateMcpHeaderDefinition(
schemaFor({ type: 'string', 'x-mcp-header': "!#$%&'*+-.^_`|~09Az" }),
);
assert.equal(allowed.valid, true);
});
test('requires case-insensitively unique header names across nesting levels', () => {
assertInvalid(
{
type: 'object',
properties: {
first: { type: 'string', 'x-mcp-header': 'Region' },
nested: {
type: 'object',
properties: {
second: { type: 'string', 'x-mcp-header': 'rEgIoN' },
},
},
},
},
'header_name_duplicate',
['nested', 'second'],
);
});
test('rejects annotations outside a properties-only static path', () => {
assertInvalid({ type: 'object', 'x-mcp-header': 'Root' }, 'not_statically_reachable', []);
const unreachableSchemas: Array<[string, unknown]> = [
['items', { type: 'string', 'x-mcp-header': 'Item' }],
['additionalProperties', { type: 'string', 'x-mcp-header': 'Additional' }],
['oneOf', [{ type: 'string', 'x-mcp-header': 'Choice' }]],
['$defs', { declared: { type: 'string', 'x-mcp-header': 'Definition' } }],
['patternProperties', { '^dynamic': { type: 'string', 'x-mcp-header': 'Pattern' } }],
];
for (const [keyword, subschema] of unreachableSchemas) {
assertInvalid({ type: 'object', [keyword]: subschema }, 'not_statically_reachable', [
`<${keyword}>`,
]);
}
});
});
test('partitioning excludes only malformed Tools and preserves valid references', () => {
const valid = {
name: 'search',
inputSchema: schemaFor({ type: 'string', 'x-mcp-header': 'Region' }),
};
const invalid = {
name: 'calculate',
inputSchema: schemaFor({ type: 'number', 'x-mcp-header': 'Ratio' }),
};
const plain = { name: 'echo', inputSchema: { type: 'object' } };
const result = partitionMcpHeaderToolDefinitions([valid, invalid, plain]);
assert.deepEqual(
result.valid.map(({ tool }) => tool),
[valid, plain],
);
assert.deepEqual(result.rejected, [
{
toolName: 'calculate',
issue: { code: 'property_type_unsupported', path: ['value'] },
},
]);
});
describe('SEP-2243 exclusion warning', () => {
test('reports the total and a capped sample using stable reason codes', () => {
const rejections = Array.from({ length: 8 }, (_, index) =>
rejection(
`tool-${index}`,
index % 2 === 0 ? 'header_name_invalid' : 'property_type_unsupported',
),
);
const warning = formatMcpHeaderExclusionWarning(rejections);
assert.ok(warning);
assert.match(warning, /excluded 8 Tool definition/u);
assert.match(warning, /\[header_name_invalid\]/u);
assert.match(warning, /\[property_type_unsupported\]/u);
assert.match(warning, /3 more not shown/u);
assert.doesNotMatch(warning, /tool-5-/u);
assert.ok(warning.length <= MCP_HEADER_WARNING_LENGTH_LIMIT);
});
test('sanitizes control characters and always honors the rendered-length cap', () => {
const warning = formatMcpHeaderExclusionWarning([
rejection(`line\r\n\u2028\u2029${'😀\\'.repeat(200)}`, 'header_name_invalid'),
rejection('second', 'header_name_duplicate'),
rejection('third', 'annotation_not_string'),
rejection('fourth', 'header_name_empty'),
rejection('fifth', 'not_statically_reachable'),
]);
assert.ok(warning);
assert.doesNotMatch(warning, /[\r\n\u2028\u2029]/u);
assert.match(warning, /…/u);
assert.ok(warning.length <= MCP_HEADER_WARNING_LENGTH_LIMIT);
});
test('redacts secret-shaped Tool names before logging them', () => {
const secret = 'sk-ant-1234567890abcdef';
const warning = formatMcpHeaderExclusionWarning([
rejection(`tool-${secret}`, 'header_name_invalid'),
]);
assert.ok(warning);
assert.doesNotMatch(warning, new RegExp(secret, 'u'));
assert.match(warning, /\[redacted\]/u);
});
test('returns undefined when no Tool was excluded', () => {
assert.equal(formatMcpHeaderExclusionWarning([]), undefined);
});
});
describe('SEP-2243 call-time integer validation', () => {
const definition = validateMcpHeaderDefinition({
type: 'object',
properties: {
routing: {
type: 'object',
properties: {
shard: { type: 'integer', 'x-mcp-header': 'Shard' },
},
},
},
});
assert.equal(definition.valid, true);
if (!definition.valid) throw new Error('test setup is invalid');
test('accepts safe boundaries and leaves other schema validation to the caller', () => {
for (const value of [
Number.MIN_SAFE_INTEGER,
Number.MAX_SAFE_INTEGER,
undefined,
null,
'not-a-number',
1.5,
Number.POSITIVE_INFINITY,
]) {
assert.deepEqual(
validateMcpHeaderArguments(definition.declarations, {
routing: { shard: value },
}),
{ valid: true },
);
}
});
test('returns a stable local failure for unsafe integer arguments', () => {
assert.deepEqual(
validateMcpHeaderArguments(definition.declarations, {
routing: { shard: Number.MAX_SAFE_INTEGER + 1 },
}),
{
valid: false,
code: 'unsafe_integer_argument',
path: ['routing', 'shard'],
},
);
});
});
function schemaFor(property: Record<string, unknown>): Record<string, unknown> {
return {
type: 'object',
properties: { value: property },
};
}
function assertInvalid(
schema: unknown,
code: McpHeaderToolRejection['issue']['code'],
path: readonly string[],
): void {
const result = validateMcpHeaderDefinition(schema);
assert.equal(result.valid, false);
if (result.valid) return;
assert.deepEqual(result.issue, { code, path });
}
function rejection(
toolName: string,
code: McpHeaderToolRejection['issue']['code'],
): McpHeaderToolRejection {
return { toolName, issue: { code, path: ['value'] } };
}
@@ -0,0 +1,293 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import assert from 'node:assert/strict';
import { mkdtemp, readFile, realpath, rm } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { fileURLToPath } from 'node:url';
import { afterEach, describe, test } from 'node:test';
import { MCP_CONFIG_VERSION, type McpConfigFile, type McpProtocolPreference } from '@maka/core/mcp';
import { McpClientManager } from '../index.js';
const legacyFixturePath = fileURLToPath(
new URL('../__fixtures__/stdio-server.js', import.meta.url),
);
const dualEraFixturePath = fileURLToPath(
new URL('../__fixtures__/dual-era-stdio-server.js', import.meta.url),
);
const managers: McpClientManager[] = [];
const roots: string[] = [];
afterEach(async () => {
await Promise.all(managers.splice(0).map((manager) => manager.close()));
await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true })));
});
describe('McpClientManager stdio protocol negotiation', { concurrency: false }, () => {
test('omitted and explicit legacy preferences each start exactly one child', async () => {
for (const protocol of [undefined, 'legacy'] as const) {
const fixture = await fixtureConfig('legacy', protocol);
const manager = createManager();
await manager.sync(fixture.config);
assert.deepEqual(manager.status('fixture')?.negotiatedProtocol, {
era: 'legacy',
revision: '2025-11-25',
});
assert.equal(
uniquePids(await waitForEvents(fixture.log, (events) => events.length > 0)).length,
1,
);
await manager.close();
}
});
test('auto probes a legacy server with a reaped sibling before the actual child', async () => {
const fixture = await fixtureConfig('legacy', 'auto');
const manager = createManager();
await manager.sync(fixture.config);
assert.deepEqual(manager.status('fixture')?.negotiatedProtocol, {
era: 'legacy',
revision: '2025-11-25',
});
const events = await waitForEvents(fixture.log, (current) => uniquePids(current).length === 2);
assertProbeBeforeActual(events);
});
test('auto connects to a modern-only server after an isolated matching probe', async () => {
const fixture = await fixtureConfig('modern-only', 'auto');
const manager = createManager();
await manager.sync(fixture.config);
assert.deepEqual(manager.status('fixture')?.negotiatedProtocol, {
era: 'modern',
revision: '2026-07-28',
});
const events = await waitForEvents(fixture.log, (current) => uniquePids(current).length === 2);
const [probePid, actualPid] = assertProbeBeforeActual(events);
const starts = events.filter((event) => event.event === 'start');
assert.equal(starts.length, 2);
assert.deepEqual(
starts.map(({ execPath, argv, cwd, fixtureEnv }) => ({ execPath, argv, cwd, fixtureEnv })),
[
{
execPath: process.execPath,
argv: [dualEraFixturePath, '--modern-only'],
cwd: fixture.root,
fixtureEnv: 'same-launch-input',
},
{
execPath: process.execPath,
argv: [dualEraFixturePath, '--modern-only'],
cwd: fixture.root,
fixtureEnv: 'same-launch-input',
},
],
);
assert.equal(isPidAlive(probePid), false);
assert.equal(isPidAlive(actualPid), true);
assert.deepEqual(manager.status('fixture')?.stderrTail, [
`stdio fixture dual-era pid=${actualPid}`,
]);
await manager.close();
await waitForEvents(fixture.log, (current) =>
current.some((event) => event.event === 'exit' && event.pid === actualPid),
);
assert.equal(isPidAlive(actualPid), false);
});
test('an exact modern pin connects to a modern-only server without downgrade', async () => {
const fixture = await fixtureConfig('modern-only', '2026-07-28');
const manager = createManager();
await manager.sync(fixture.config);
assert.deepEqual(manager.status('fixture')?.negotiatedProtocol, {
era: 'modern',
revision: '2026-07-28',
});
const events = await waitForEvents(fixture.log, (current) => uniquePids(current).length === 2);
const [probePid, actualPid] = assertProbeBeforeActual(events);
assert.equal(isPidAlive(probePid), false);
assert.equal(isPidAlive(actualPid), true);
});
test('an exact modern pin leaves no actual child after a legacy-only rejection', async () => {
const fixture = await fixtureConfig('legacy', '2026-07-28');
const manager = createManager();
await manager.sync(fixture.config);
assert.equal(manager.status('fixture')?.state, 'error');
assert.equal(manager.status('fixture')?.negotiatedProtocol, undefined);
assert.deepEqual(manager.toolSnapshot().tools, []);
const events = await waitForEvents(fixture.log, (current) =>
current.some((event) => event.event === 'exit'),
);
assert.equal(uniquePids(events).length, 1);
assert.equal(isPidAlive(uniquePids(events)[0]!), false);
});
test('a pre-aborted auto connect starts no child', async () => {
const fixture = await fixtureConfig('modern-only', 'auto');
const manager = createManager();
let cancelled = false;
manager.onChange((status) => {
if (!cancelled && status.serverId === 'fixture' && status.state === 'connecting') {
cancelled = manager.cancelConnect('fixture');
}
});
await manager.sync(fixture.config);
assert.equal(cancelled, true);
assert.equal(manager.status('fixture')?.state, 'disconnected');
assert.deepEqual(await readEvents(fixture.log), []);
});
test('aborting during a delayed probe reaps it and never starts the actual child', async () => {
const fixture = await fixtureConfig('modern-only', 'auto', {
MAKA_MCP_STDIO_FACTORY_DELAY_MS: '30000',
});
const manager = createManager();
const sync = manager.sync(fixture.config);
await waitForEvents(fixture.log, (events) =>
events.some((event) => event.event === 'factory' && event.era === 'modern'),
);
assert.equal(manager.cancelConnect('fixture'), true);
await sync;
const events = await waitForEvents(fixture.log, (current) =>
current.some((event) => event.event === 'exit'),
);
assert.equal(uniquePids(events).length, 1);
assert.equal(manager.status('fixture')?.state, 'disconnected');
assert.equal(manager.status('fixture')?.negotiatedProtocol, undefined);
assert.deepEqual(manager.toolSnapshot().tools, []);
});
});
type StdioFixtureEvent = {
event: string;
fixture: string;
pid: number;
execPath?: string;
argv?: string[];
cwd?: string;
fixtureEnv?: string | null;
era?: 'legacy' | 'modern';
};
async function fixtureConfig(
kind: 'legacy' | 'modern-only',
protocol?: McpProtocolPreference,
extraEnv: Record<string, string> = {},
): Promise<{ config: McpConfigFile; log: string; root: string }> {
const root = await realpath(await mkdtemp(join(tmpdir(), 'maka-mcp-stdio-negotiation-')));
roots.push(root);
const log = join(root, 'events.jsonl');
const fixturePath = kind === 'legacy' ? legacyFixturePath : dualEraFixturePath;
const config: McpConfigFile = {
version: MCP_CONFIG_VERSION,
mcpServers: {
fixture: {
command: process.execPath,
args: [fixturePath, ...(kind === 'modern-only' ? ['--modern-only'] : [])],
cwd: root,
env: {
MAKA_MCP_STDIO_EVENT_LOG: log,
MAKA_MCP_STDIO_FIXTURE_VALUE: 'same-launch-input',
...extraEnv,
},
...(protocol === undefined ? {} : { protocol }),
},
},
};
return { config, log, root };
}
function createManager(): McpClientManager {
const manager = new McpClientManager({
timeouts: { stdioConnectMs: 5_000, listToolsMs: 5_000, callToolMs: 5_000 },
});
managers.push(manager);
return manager;
}
async function waitForEvents(
path: string,
predicate: (events: StdioFixtureEvent[]) => boolean,
timeoutMs = 5_000,
): Promise<StdioFixtureEvent[]> {
const deadline = Date.now() + timeoutMs;
while (Date.now() < deadline) {
const events = await readEvents(path);
if (predicate(events)) return events;
await new Promise((resolve) => setTimeout(resolve, 10));
}
const events = await readEvents(path);
assert.fail(`timed out waiting for stdio fixture events: ${JSON.stringify(events)}`);
}
async function readEvents(path: string): Promise<StdioFixtureEvent[]> {
let source: string;
try {
source = await readFile(path, 'utf8');
} catch (error) {
if ((error as NodeJS.ErrnoException).code === 'ENOENT') return [];
throw error;
}
return source
.split('\n')
.filter(Boolean)
.map((line) => JSON.parse(line) as StdioFixtureEvent);
}
function uniquePids(events: StdioFixtureEvent[]): number[] {
return [...new Set(events.filter((event) => event.event === 'start').map((event) => event.pid))];
}
function assertProbeBeforeActual(events: StdioFixtureEvent[]): [number, number] {
const pids = uniquePids(events);
assert.equal(pids.length, 2, JSON.stringify(events));
const [probePid, actualPid] = pids as [number, number];
const probeExit = events.findIndex((event) => event.event === 'exit' && event.pid === probePid);
const actualStart = events.findIndex(
(event) => event.event === 'start' && event.pid === actualPid,
);
assert.ok(probeExit >= 0, JSON.stringify(events));
assert.ok(probeExit < actualStart, JSON.stringify(events));
return [probePid, actualPid];
}
function isPidAlive(pid: number): boolean {
try {
process.kill(pid, 0);
return true;
} catch (error) {
return (error as NodeJS.ErrnoException).code === 'EPERM';
}
}
@@ -0,0 +1,85 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import assert from 'node:assert/strict';
import { describe, test } from 'node:test';
import {
createMcpToolBinding,
parseMcpToolBinding,
type McpToolBindingIdentity,
} from '../tool-binding.js';
const identity: McpToolBindingIdentity = {
managerId: 'abcdefghijklmnopqrstuv',
connectionGeneration: 1,
serverId: 'fixture',
toolName: 'echo',
definitionFingerprint: 'a'.repeat(43),
};
describe('MCP Tool binding', () => {
test('round-trips only the canonical bounded encoding', () => {
const binding = createMcpToolBinding(identity);
assert.deepEqual(parseMcpToolBinding(binding), {
managerId: identity.managerId,
connectionGeneration: identity.connectionGeneration,
});
assert.ok(binding.length <= 96);
assert.equal(parseMcpToolBinding(binding.replace('.1.', '.01.')), undefined);
});
test('rejects malformed, oversized, and invalid generation identities', () => {
assert.equal(parseMcpToolBinding('not-a-binding'), undefined);
assert.equal(parseMcpToolBinding(`mcpb1.${'a'.repeat(97)}`), undefined);
assert.throws(
() => createMcpToolBinding({ ...identity, connectionGeneration: 0 }),
/Invalid MCP tool binding identity/u,
);
});
test('keeps the opaque binding bounded without restricting server or Tool names', () => {
const short = createMcpToolBinding(identity);
const long = createMcpToolBinding({ ...identity, toolName: 'x'.repeat(10_000) });
const emptyTool = createMcpToolBinding({ ...identity, toolName: '' });
const emptyServer = createMcpToolBinding({ ...identity, serverId: '' });
assert.notEqual(long, short);
assert.notEqual(emptyTool, short);
assert.notEqual(emptyServer, short);
assert.equal(long.length, short.length);
assert.equal(emptyTool.length, short.length);
assert.equal(emptyServer.length, short.length);
assert.deepEqual(parseMcpToolBinding(long), {
managerId: identity.managerId,
connectionGeneration: identity.connectionGeneration,
});
});
test('changes when any consistency identity input changes', () => {
const binding = createMcpToolBinding(identity);
assert.notEqual(createMcpToolBinding({ ...identity, connectionGeneration: 2 }), binding);
assert.notEqual(createMcpToolBinding({ ...identity, serverId: 'other' }), binding);
assert.notEqual(createMcpToolBinding({ ...identity, toolName: 'other' }), binding);
assert.notEqual(
createMcpToolBinding({ ...identity, definitionFingerprint: 'b'.repeat(43) }),
binding,
);
});
});
@@ -0,0 +1,89 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import assert from 'node:assert/strict';
import { test } from 'node:test';
import { SdkError, SdkErrorCode } from '@modelcontextprotocol/client';
import { McpToolCallError, normalizeToolCallError } from '../tool-call-error.js';
test('normalizes the SDK unsupported-result error to the stable Maka boundary', () => {
const causes = [
new SdkError(
SdkErrorCode.UnsupportedResultType,
"Unsupported result type 'input_required' for tools/call",
),
...["'task'", "'inputRequests'", "'requestState'"].map(
(marker) =>
new SdkError(
SdkErrorCode.InvalidResult,
`Invalid result for tools/call: content is required when the body carries ${marker} — another result family cannot default into an empty tools/call success`,
),
),
];
for (const cause of causes) {
const error = normalizeToolCallError('fixture', 'deferred', cause);
assert.ok(error instanceof McpToolCallError);
assert.equal(error.serverId, 'fixture');
assert.equal(error.toolName, 'deferred');
assert.match(error.message, /unsupported deferred tool result/u);
assert.equal(error.cause, cause);
}
});
test('preserves the invalid-result classification for unrelated schema failures', () => {
const error = normalizeToolCallError(
'fixture',
'invalid',
new SdkError(SdkErrorCode.InvalidResult, 'Invalid result for tools/call: not an object'),
);
assert.ok(error instanceof McpToolCallError);
assert.match(error.message, /invalid tool result/u);
assert.doesNotMatch(error.message, /unsupported deferred/u);
});
test('wraps generic SDK and transport failures without exposing their message', () => {
const cause = new SyntaxError('sk-live-secret-token-value\r\nforged\u2028message');
const error = normalizeToolCallError('fixture', 'parse', cause);
assert.ok(error instanceof McpToolCallError);
assert.notEqual(error, cause);
assert.equal(error.cause, cause);
assert.match(error.message, /tool call failed/u);
assert.doesNotMatch(error.message, /sk-live|forged/u);
assert.doesNotMatch(error.message, /[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/u);
});
test('keeps raw identity fields while rendering a bounded log-safe message', () => {
const serverId = 'server\u2028token=sk-live-server-secret';
const toolName = `tool\r\n${'x'.repeat(100)}`;
const error = new McpToolCallError(
serverId,
toolName,
`failed with password=tool-secret ${'detail'.repeat(500)}`,
);
assert.equal(error.serverId, serverId);
assert.equal(error.toolName, toolName);
assert.doesNotMatch(error.message, /[\r\n\u2028\u2029]/u);
assert.doesNotMatch(error.message, /sk-live|tool-secret/u);
assert.ok(error.message.length < 2_250);
});
@@ -0,0 +1,50 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import assert from 'node:assert/strict';
import { describe, test } from 'node:test';
import type { Tool } from '@modelcontextprotocol/client';
import { fingerprintMcpToolDefinition } from '../tool-definition.js';
describe('MCP Tool definition fingerprint', () => {
test('rejects oversized and excessively deep definitions', () => {
assert.throws(
() =>
fingerprintMcpToolDefinition({
name: 'large',
description: 'x'.repeat(1_048_577),
inputSchema: { type: 'object' },
}),
/tool definition exceeds/u,
);
let schema: Record<string, unknown> = { type: 'string' };
for (let depth = 0; depth < 101; depth += 1) {
schema = { type: 'object', properties: { child: schema } };
}
assert.throws(
() =>
fingerprintMcpToolDefinition({
name: 'deep',
inputSchema: schema as Tool['inputSchema'],
}),
/definition exceeds depth/u,
);
});
});
@@ -0,0 +1,169 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import assert from 'node:assert/strict';
import { describe, test } from 'node:test';
import type { Tool } from '@modelcontextprotocol/client';
import {
discoverMcpTools,
type McpToolDiscoveryLimits,
type McpToolPage,
type McpToolPageSource,
} from '../tool-discovery.js';
describe('discoverMcpTools', () => {
test('treats an empty nextCursor as an opaque continuation', async () => {
const source = sourceFromPages([
{ tools: [tool('first')], nextCursor: '' },
{ tools: [tool('second')] },
]);
const result = await discoverMcpTools(source, 'fixture', 25);
assert.deepEqual(
result.map(({ definition }) => definition.name),
['first', 'second'],
);
assert.deepEqual(source.cursors, [undefined, '']);
});
test('rejects a repeated cursor without fetching another page', async () => {
const source = sourceFromPages([
{ tools: [tool('first')], nextCursor: 'again' },
{ tools: [tool('second')], nextCursor: 'again' },
]);
await assert.rejects(discoverMcpTools(source, 'fixture', 25), /repeated a tools cursor/u);
assert.deepEqual(source.cursors, [undefined, 'again']);
});
test('rejects duplicate tool names across pages', async () => {
const source = sourceFromPages([
{ tools: [tool('same')], nextCursor: 'next' },
{ tools: [tool('same')] },
]);
await assert.rejects(discoverMcpTools(source, 'fixture', 25), /duplicate tool "same"/u);
});
test('bounds and redacts duplicate Tool names in diagnostics', async () => {
const name = `token=sk-live-\u2028${'secret'.repeat(50)}`;
const source = sourceFromPages([{ tools: [tool(name), tool(name)] }]);
await assert.rejects(
discoverMcpTools(source, 'fixture', 25),
(error: unknown) =>
error instanceof Error &&
error.message.length < 256 &&
error.message.includes('[redacted]') &&
!error.message.includes('sk-live') &&
!/[\r\n\u2028\u2029]/u.test(error.message),
);
});
test('stops within an oversized tool page', async () => {
const source = sourceFromPages([{ tools: [tool('one'), tool('two')] }]);
await assert.rejects(
discoverMcpTools(source, 'fixture', 25, limits({ maxTools: 1 })),
/exceeded 1 tools/u,
);
assert.equal(source.cursors.length, 1);
});
test('does not fetch beyond the page limit', async () => {
const source = sourceFromPages([
{ tools: [tool('one')], nextCursor: 'two' },
{ tools: [tool('two')], nextCursor: 'three' },
{ tools: [tool('unreachable')] },
]);
await assert.rejects(
discoverMcpTools(source, 'fixture', 25, limits({ maxPages: 2 })),
/exceeded 2 tool pages/u,
);
assert.deepEqual(source.cursors, [undefined, 'two']);
});
test('rejects cumulative definition bytes across pages without fetching another page', async () => {
const source = sourceFromPages([
{
tools: [{ ...tool('first'), description: 'a'.repeat(400) }],
nextCursor: 'second',
},
{
tools: [{ ...tool('second'), description: 'b'.repeat(400) }],
nextCursor: 'unreachable',
},
{ tools: [tool('unreachable')] },
]);
await assert.rejects(
discoverMcpTools(source, 'fixture', 25, limits({ maxDefinitionBytes: 700 })),
/exceeded 700 tool definition bytes/u,
);
assert.deepEqual(source.cursors, [undefined, 'second']);
});
test('preflights definition depth before cloning it into the snapshot candidate', async () => {
let schema: Record<string, unknown> = { type: 'string' };
for (let depth = 0; depth < 101; depth += 1) {
schema = { type: 'object', properties: { child: schema } };
}
const source = sourceFromPages([
{
tools: [{ name: 'deep', inputSchema: schema as Tool['inputSchema'] }],
},
]);
await assert.rejects(discoverMcpTools(source, 'fixture', 25), /tool definition exceeds depth/u);
});
});
function tool(name: string): Tool {
return {
name,
inputSchema: { type: 'object' },
};
}
function limits(overrides: Partial<McpToolDiscoveryLimits>): McpToolDiscoveryLimits {
return {
maxPages: 10,
maxTools: 10,
maxDefinitionBytes: 10_000,
...overrides,
};
}
function sourceFromPages(
pages: readonly McpToolPage[],
): McpToolPageSource & { cursors: Array<string | undefined> } {
const remaining = [...pages];
const cursors: Array<string | undefined> = [];
return {
cursors,
async requestToolsPage(cursor) {
cursors.push(cursor);
const page = remaining.shift();
if (!page) throw new Error('unexpected tools/list request');
return page;
},
};
}
@@ -0,0 +1,100 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import assert from 'node:assert/strict';
import { describe, test } from 'node:test';
import type { Tool } from '@modelcontextprotocol/client';
import { McpToolCallPreparer } from '../tool-output-validation.js';
describe('MCP Tool output validation preparation', () => {
test('strips only the SDK outputSchema view and validates from the owned definition', () => {
const preparer = new McpToolCallPreparer();
const definition: Tool = {
name: 'echo',
inputSchema: {
type: 'object',
properties: {
value: {
type: 'string',
'x-vendor-extension': 'opaque',
},
},
},
outputSchema: {
type: 'object',
properties: { ok: { type: 'boolean' } },
required: ['ok'],
additionalProperties: false,
},
};
const prepared = preparer.prepare(definition);
assert.equal(prepared.ok, true);
if (!prepared.ok) return;
assert.equal(prepared.value.definitionForSdk.outputSchema, undefined);
assert.deepEqual(prepared.value.definitionForSdk.inputSchema, definition.inputSchema);
assert.notEqual(prepared.value.definitionForSdk, definition);
assert.ok(definition.outputSchema);
assert.equal(prepared.value.validateOutput?.({ ok: true }).valid, true);
assert.equal(prepared.value.validateOutput?.({ wrong: true }).valid, false);
});
test('reports malformed schemas during pre-wire preparation', () => {
const prepared = new McpToolCallPreparer().prepare({
name: 'invalid',
inputSchema: { type: 'object' },
outputSchema: { type: 'string', pattern: '[' },
});
assert.equal(prepared.ok, false);
});
test('compiles each tool against its own schema when $ids collide', () => {
const preparer = new McpToolCallPreparer();
const first = preparer.prepare({
name: 'first',
inputSchema: { type: 'object' },
outputSchema: {
$id: 'shared-id',
type: 'object',
properties: { a: { type: 'number' } },
required: ['a'],
},
});
const second = preparer.prepare({
name: 'second',
inputSchema: { type: 'object' },
outputSchema: {
$id: 'shared-id',
type: 'object',
properties: { b: { type: 'number' } },
required: ['b'],
},
});
assert.equal(first.ok, true);
assert.equal(second.ok, true);
if (!first.ok || !second.ok) return;
assert.equal(first.value.validateOutput?.({ a: 1 }).valid, true);
assert.equal(first.value.validateOutput?.({ b: 1 }).valid, false);
assert.equal(second.value.validateOutput?.({ b: 1 }).valid, true);
assert.equal(second.value.validateOutput?.({ a: 1 }).valid, false);
});
});
@@ -0,0 +1,153 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import assert from 'node:assert/strict';
import { describe, it } from 'node:test';
import { assertTransportSecurity, urlProvenance } from '../transport-security.js';
describe('transport security provenance', () => {
const remoteRoot = urlProvenance(new URL('https://api.example.com/mcp'));
const loopbackRoot = urlProvenance(new URL('http://127.0.0.1:8080/mcp'));
it('allows public https regardless of provenance', () => {
assert.doesNotThrow(() =>
assertTransportSecurity(new URL('https://as.example.com/token'), remoteRoot),
);
assert.doesNotThrow(() =>
assertTransportSecurity(new URL('https://as.example.com/token'), loopbackRoot),
);
});
it('refuses remotely supplied https aimed back into the machine or network', () => {
// A remote server's OAuth metadata naming an internal https destination
// is a request-forgery primitive (blind SSRF): the client would issue
// the GET/POST from inside the user's network.
for (const url of [
'https://127.0.0.1:8443/latest/meta-data/',
'https://localhost:8443/admin',
'https://169.254.169.254/latest/meta-data/',
'https://192.168.1.1/router',
'https://10.0.0.5/internal',
'https://172.16.0.9/internal',
'https://100.64.0.1/cgnat',
]) {
assert.throws(() => assertTransportSecurity(new URL(url), remoteRoot), /refused remotely/u);
}
// A loopback trust root keeps its local machine reachable; an internal
// configured endpoint keeps its own network reachable.
assert.doesNotThrow(() =>
assertTransportSecurity(new URL('https://127.0.0.1:8443/token'), loopbackRoot),
);
const internalRoot = urlProvenance(new URL('https://10.1.2.3/mcp'));
assert.doesNotThrow(() =>
assertTransportSecurity(new URL('https://10.0.0.5/token'), internalRoot),
);
assert.throws(
() => assertTransportSecurity(new URL('https://127.0.0.1:8443/x'), internalRoot),
/refused remotely/u,
);
// Privately-RESOLVING names are accepted risk (no resolve here): a
// hostname passes even under a remote root.
assert.doesNotThrow(() =>
assertTransportSecurity(new URL('https://intranet.corp/token'), remoteRoot),
);
});
it('refuses IPv6-mapped spellings of machine-local and private destinations', () => {
// WHATWG canonicalizes `[::ffff:127.0.0.1]` to `[::ffff:7f00:1]` before
// the gate ever sees it — the classification is by parsed bytes, so
// every spelling of the same address lands on the same side. Note the
// asymmetry: these are caught as PRIVATE (isLoopbackHost deliberately
// stays spelling-strict, so cleartext to the mapped loopback is still
// refused by the http branch).
for (const url of [
'https://[::ffff:127.0.0.1]:8443/latest/meta-data/',
'https://[::ffff:192.168.1.1]/router',
'https://[0:0:0:0:0:ffff:10.0.0.5]/internal',
'https://[64:ff9b::192.168.1.1]/nat64',
'https://[fe9a::1]/link-local',
// Deprecated IPv4-compatible ::/96 — the third byte-level embedding,
// arriving through the same remote-provenance path a real one would.
'https://[::192.168.1.1]/compat',
'https://[::127.0.0.1]:8443/compat-loopback',
'https://[::]/unspecified',
'https://[::ffff:0:0]:8443/mapped-unspecified',
'https://[64:ff9b:1:c0a8:1:100::]/local-nat64',
'https://[0::ffff:0:192.168.1.1]/siit',
// `https://0/` canonicalizes to 0.0.0.0 and reaches the local machine.
'https://0.0.0.0:8443/unspecified-v4',
'https://0/short-form',
]) {
assert.throws(() => assertTransportSecurity(new URL(url), remoteRoot), /refused remotely/u);
}
// Public IPv6 stays reachable — that is what real OAuth endpoints on
// IPv6 look like.
assert.doesNotThrow(() =>
assertTransportSecurity(new URL('https://[2606:4700::1]/token'), remoteRoot),
);
// Cleartext to the mapped loopback is refused by the strict loopback
// predicate, exactly as before.
assert.throws(
() => assertTransportSecurity(new URL('http://[::ffff:127.0.0.1]:8080/mcp'), remoteRoot),
/non-loopback hosts require https/u,
);
});
it('never allows cleartext http off the machine', () => {
assert.throws(
() => assertTransportSecurity(new URL('http://api.example.com/mcp'), remoteRoot),
/non-loopback hosts require https/u,
);
assert.throws(
() => assertTransportSecurity(new URL('http://10.0.0.5/mcp'), loopbackRoot),
/non-loopback hosts require https/u,
);
});
it('refuses a remotely supplied loopback destination when the server is remote', () => {
// A remote https server redirecting (or pointing its OAuth metadata) at
// the user's own machine is a pivot, not a convenience.
assert.throws(
() => assertTransportSecurity(new URL('http://127.0.0.1:9999/steal'), remoteRoot),
/remotely supplied loopback/u,
);
assert.throws(
() => assertTransportSecurity(new URL('http://localhost:22/'), remoteRoot),
/remotely supplied loopback/u,
);
});
it('allows loopback http when the user configured a loopback trust root', () => {
assert.doesNotThrow(() =>
assertTransportSecurity(new URL('http://127.0.0.1:8080/mcp'), loopbackRoot),
);
// A local AS on a different loopback port is part of the same local
// trust decision the user already made.
assert.doesNotThrow(() =>
assertTransportSecurity(new URL('http://127.0.0.1:9000/authorize'), loopbackRoot),
);
});
it('refuses non-HTTP schemes outright', () => {
assert.throws(
() => assertTransportSecurity(new URL('file:///etc/passwd'), loopbackRoot),
/non-HTTP/u,
);
});
});
+258
View File
@@ -0,0 +1,258 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
// packages/mcp/src/credential-coordinator.ts
//
// The single owner of MCP OAuth credential state transitions. Every read,
// write and delete for a server's stored record flows through one
// per-server lane here, every record write carries a monotonically
// increasing version validated against the basis that was read, and every
// terminal erase advances a PERSISTED per-server generation — a tombstone
// that outlives the process. Together these make a complete OAuth state
// transition atomic — not merely each storage call — and make revocation
// terminal in every interleaving, including across processes:
//
// - a flow that began before a logout may finish its reads, but its writes
// are refused: in-process by the epoch, cross-process by the generation
// it captured on its first read no longer matching the tombstone's;
// - a write that began before the logout completes first — the queued
// erase lands after it (lane order);
// - a stale flow cannot delete a record a newer flow just stored (epoch
// check on delete);
// - an external writer (another process editing the backing store) trips
// the version/CAS check instead of being silently overwritten, when the
// storage backend exposes compare-and-set;
// - deletion never leaves "absent" behind: erase writes a tombstone record
// carrying only the advanced generation, so a cross-process flow cannot
// CAS against absence (`expectedVersion = null`) and resurrect
// credentials the user revoked.
import type { McpOAuthRecord, McpOAuthStorage } from './oauth.js';
/** Guards one flow's writes: the epoch pins in-process revocation, the
* captured generation pins cross-process revocation, and the optional
* abort signal fences writes landing after the flow's round was abandoned
* (a timed-out login must not overwrite a newer round's state). */
interface FlowGuard {
epoch: number;
generation?: number;
/** The record version this flow last observed or produced. A write whose
* basis carries a DIFFERENT version means another writer (a concurrent
* refresh in this or another process) rotated the record mid-flow: the
* stale flow must not overwrite — or delete — the fresh material. */
version?: number;
signal?: AbortSignal;
}
export class McpCredentialCoordinator {
private readonly epochs = new Map<string, number>();
private readonly lanes = new Map<string, Promise<unknown>>();
constructor(private readonly storage: McpOAuthStorage) {}
/** Serializes an operation into the server's credential lane. */
run<T>(serverId: string, op: () => Promise<T>): Promise<T> {
const previous = this.lanes.get(serverId) ?? Promise.resolve();
const next = previous.then(op, op);
this.lanes.set(
serverId,
next.then(
() => {},
() => {},
),
);
return next;
}
epoch(serverId: string): number {
return this.epochs.get(serverId) ?? 0;
}
/** Terminal erase: bumps the in-process epoch first (in-flight flows in
* this process become stale immediately), then — inside the lane, behind
* any write already in progress — replaces the record with a tombstone
* whose generation is advanced by one. The tombstone is what makes the
* revocation terminal for OTHER processes: their flows captured the old
* generation and every later write verifies it against the stored one.
* A failure propagates — callers must not proceed as if the credentials
* were gone.
*
* The optional signal fences an ABANDONED erase: a logout whose round
* timed out must not resume later, adopt whatever record a newer login
* just stored as its basis, and tombstone the fresh tokens. */
async erase(serverId: string, options: { signal?: AbortSignal } = {}): Promise<void> {
this.epochs.set(serverId, this.epoch(serverId) + 1);
await this.run(serverId, async () => {
this.assertNotAbandoned(serverId, options.signal);
const basis = await this.storage.get(serverId);
// Re-check after the read: the abandonment may have landed while the
// storage read was in flight — committing past it would erase a
// record the caller no longer owns.
this.assertNotAbandoned(serverId, options.signal);
// Absence still gets a tombstone: a cross-process flow that captured
// generation 0 on absence must not CAS its credentials back in after
// this revocation.
const tombstone: McpOAuthRecord = {
generation: (basis?.generation ?? 0) + 1,
version: (basis?.version ?? 0) + 1,
};
await this.commit(serverId, basis, tombstone);
});
}
private assertNotAbandoned(serverId: string, signal?: AbortSignal): void {
if (signal?.aborted) {
throw new Error(`MCP credential erase for "${serverId}" was abandoned before it landed`);
}
}
/** One atomic state transition pinned to the flow guard: read the
* current record, verify the guard (epoch, captured generation, abort),
* apply, stamp the next version, and write — all inside the lane, with
* the version validated against the read basis (and, when the backend
* supports compare-and-set, against the stored bytes). */
transition(
serverId: string,
guard: FlowGuard,
apply: (record: McpOAuthRecord) => McpOAuthRecord,
): Promise<McpOAuthRecord> {
return this.run(serverId, async () => {
this.assertGuard(serverId, guard);
const basis = await this.storage.get(serverId);
// Re-check after the read: the abort (or a logout) may have landed
// while the storage read was in flight, and committing past it would
// persist a verifier or token for an abandoned round.
this.assertGuard(serverId, guard);
const basisGeneration = basis?.generation ?? 0;
if (guard.generation !== undefined && basisGeneration !== guard.generation) {
throw new Error(`MCP credentials for "${serverId}" were revoked during the operation`);
}
if (guard.version !== undefined && (basis?.version ?? 0) !== guard.version) {
throw new Error(
`MCP credentials for "${serverId}" were rotated by another writer during the operation`,
);
}
const record = apply(basis ? { ...basis } : {});
// The generation is the coordinator's own bookkeeping: flows never
// set it, and a write never advances it — only erase() does.
record.generation = basisGeneration;
record.version = (basis?.version ?? 0) + 1;
await this.commit(serverId, basis, record);
return record;
});
}
/** A storage view for one auth flow, pinned to the epoch at flow start
* and to the persisted generation observed on the flow's first access.
* The SDK-facing provider talks to this; every operation lands in the
* lane, and writes/deletes are refused once the epoch or generation
* moved — or once the flow's round was aborted. */
flowStorage(serverId: string, options: { signal?: AbortSignal } = {}): McpOAuthStorage {
const guard: FlowGuard = { epoch: this.epoch(serverId), ...options };
const capture = (record: McpOAuthRecord | undefined) => {
guard.generation ??= record?.generation ?? 0;
guard.version ??= record?.version ?? 0;
};
// The flow's own writes advance its version fence; anyone ELSE's write
// in between leaves the fence behind the stored version and the next
// transition refuses instead of overwriting the rotation.
const advance = (record: McpOAuthRecord) => {
guard.version = record.version ?? guard.version;
return record;
};
return {
get: (id) =>
this.run(serverId, async () => {
const record = await this.storage.get(id);
capture(record);
return record;
}),
set: (id, record) =>
this.transition(id, guard, (basis) => {
capture(basis);
return { ...record };
})
.then(advance)
.then(() => {}),
update: (id, apply) =>
this.transition(id, guard, (basis) => {
capture(basis);
return apply(basis);
}).then(advance),
// An in-flow invalidation clears credential material but is NOT a
// logout: the generation is preserved, not advanced, so the flow can
// continue (e.g. re-register a client) without tripping its own guard.
delete: (id) =>
this.transition(id, guard, (basis) => {
capture(basis);
return {};
})
.then(advance)
.then(() => {}),
};
}
/** A flow view whose persisted generation/version are pinned BEFORE the
* caller performs any remote await. flowStorage alone captures them on
* the first storage access, which may come after a remote probe — a
* logout in another process during that window would let the flow adopt
* the tombstone's generation as its own starting point and keep writing.
* beginFlow closes the window with one lane-ordered read up front. */
async beginFlow(
serverId: string,
options: { signal?: AbortSignal } = {},
): Promise<McpOAuthStorage> {
const view = this.flowStorage(serverId, options);
await view.get(serverId);
return view;
}
/** Lane-ordered read outside any flow (status displays, pending lookups). */
read(serverId: string): Promise<McpOAuthRecord | undefined> {
return this.run(serverId, () => this.storage.get(serverId));
}
private assertGuard(serverId: string, guard: FlowGuard): void {
if (guard.signal?.aborted) {
throw new Error(`MCP authorization for "${serverId}" was abandoned before the write landed`);
}
if (this.epoch(serverId) !== guard.epoch) {
throw new Error(`MCP credentials for "${serverId}" were cleared during the operation`);
}
}
private async commit(
serverId: string,
basis: McpOAuthRecord | undefined,
record: McpOAuthRecord,
): Promise<void> {
if (this.storage.compareAndSet) {
const result = await this.storage.compareAndSet(serverId, basis?.version ?? null, record);
if (result !== 'committed') {
// Someone outside this coordinator changed the backing store
// between our read and write. Fail closed rather than clobber.
throw new Error(
`MCP credentials for "${serverId}" changed outside the coordinator (${result})`,
);
}
return;
}
await this.storage.set(serverId, record);
}
}
@@ -0,0 +1,110 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
// packages/mcp/src/credential-oauth-storage.ts
//
// Backs MCP OAuth persistence with the app's shared credential store: one
// `mcp:<serverId>` slug per server, the whole record as one JSON secret.
// Tokens therefore live in credentials.json (0600, workspace root) beside
// every other secret in the app — never in mcp.json, which is the shareable
// config file.
//
// Lives HERE, not in the Electron app: it has no Electron dependency, and
// every process that constructs an McpClientManager over the same mcp.json
// (Desktop main, the CLI capability provider) must be able to read the
// credentials Desktop wrote — a manager without oauthStorage silently
// reports pendingAuthorization()=undefined and erases nothing on
// forgetServerCredentials.
import type { McpOAuthRecord, McpOAuthStorage } from './oauth.js';
/** The slice of @maka/storage's CredentialStore this adapter needs, stated
* structurally so @maka/mcp does not depend on @maka/storage. */
export interface McpCredentialSecretStore {
getSecret(slug: string, kind: 'oauth_token'): Promise<string | null>;
setSecret(slug: string, kind: 'oauth_token', value: string): Promise<void>;
deleteSecret(slug: string, kind?: 'oauth_token'): Promise<void>;
compareAndSetSecret?(
slug: string,
kind: 'oauth_token',
expected: string | null,
value: string,
): Promise<{ committed: true } | { committed: false; current: string | null }>;
}
const KIND = 'oauth_token' as const;
export function createCredentialMcpOAuthStorage(store: McpCredentialSecretStore): McpOAuthStorage {
return {
async get(serverId) {
const raw = await store.getSecret(slug(serverId), KIND);
if (raw === null) return undefined;
try {
return JSON.parse(raw) as McpOAuthRecord;
} catch {
// A corrupt record is indistinguishable from none: the user
// re-authorizes, and the next save overwrites it.
return undefined;
}
},
async set(serverId, record) {
await store.setSecret(slug(serverId), KIND, JSON.stringify(record));
},
async delete(serverId) {
await store.deleteSecret(slug(serverId), KIND);
},
// Maps the coordinator's version-keyed CAS onto the CredentialStore's
// raw compare-and-set, so a writer outside this process (another Maka
// instance, a hand edit) trips a conflict instead of being clobbered.
...(store.compareAndSetSecret
? {
async compareAndSet(
serverId: string,
expectedVersion: number | null,
record: McpOAuthRecord,
): Promise<'committed' | 'conflict' | 'gone'> {
const raw = await store.getSecret(slug(serverId), KIND);
const basis = raw === null ? undefined : parseRecord(raw);
if ((basis?.version ?? null) !== expectedVersion) return 'conflict';
const result = await store.compareAndSetSecret?.(
slug(serverId),
KIND,
raw,
JSON.stringify(record),
);
if (!result) return 'conflict';
if (result.committed) return 'committed';
return result.current === null ? 'gone' : 'conflict';
},
}
: {}),
};
}
function parseRecord(raw: string): McpOAuthRecord | undefined {
try {
return JSON.parse(raw) as McpOAuthRecord;
} catch {
return undefined;
}
}
function slug(serverId: string): string {
return `mcp:${serverId}`;
}
+48
View File
@@ -0,0 +1,48 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import { redactSecrets } from '@maka/core/redaction';
export const MCP_IDENTITY_DIAGNOSTIC_CODE_POINTS = 80;
export const MCP_ERROR_DIAGNOSTIC_CODE_POINTS = 2_000;
export const MCP_DIAGNOSTIC_INPUT_CODE_UNITS = 8_192;
const OVERSIZED_MCP_DIAGNOSTIC = '[MCP diagnostic omitted: input exceeded limit]';
/** Render untrusted MCP text without control spoofing, secrets, or unbounded output. */
export function formatMcpDiagnosticText(
value: string,
maxCodePoints = MCP_IDENTITY_DIAGNOSTIC_CODE_POINTS,
): string {
const outputLimit = normalizeOutputLimit(maxCodePoints);
if (value.length > MCP_DIAGNOSTIC_INPUT_CODE_UNITS) {
return [...OVERSIZED_MCP_DIAGNOSTIC].slice(0, outputLimit).join('');
}
const redacted = redactSecrets(value);
const sanitized = redacted.replace(/[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/gu, '\uFFFD');
const codePoints = [...sanitized];
if (codePoints.length <= outputLimit) return sanitized;
return `${codePoints.slice(0, outputLimit - 1).join('')}\u2026`;
}
function normalizeOutputLimit(value: number): number {
if (!Number.isSafeInteger(value) || value <= 0) {
return MCP_IDENTITY_DIAGNOSTIC_CODE_POINTS;
}
return Math.min(value, MCP_ERROR_DIAGNOSTIC_CODE_POINTS);
}
File diff suppressed because it is too large. Load diff
+371
View File
@@ -0,0 +1,371 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
// packages/mcp/src/oauth.ts
//
// OAuth support for remote MCP servers, following the MCP authorization
// model (OAuth 2.1 + RFC 9728 protected-resource discovery, PKCE always).
//
// Split of responsibilities:
// - The SDK owns the protocol: discovery, dynamic registration, PKCE,
// token exchange and refresh all live in `client/auth.js`.
// - This module owns persistence and the interactive boundary. Tokens,
// registered-client records and in-flight PKCE verifiers go through an
// injected `McpOAuthStorage` (the desktop app backs it with the shared
// CredentialStore; tests use memory). Interaction is a mode switch:
// a background connect must never open a browser, so its provider
// REFUSES the redirect (surfacing `needs-auth`), while a user-initiated
// login CAPTURES the authorization URL for the caller to open.
import type {
OAuthClientMetadata,
OAuthClientProvider,
OAuthDiscoveryState,
StoredOAuthClientInformation,
StoredOAuthTokens,
} from '@modelcontextprotocol/client';
import type { McpOAuthConfig } from '@maka/core/mcp';
/** Everything the provider persists for one server, as one JSON document. */
export interface McpOAuthRecord {
/** Monotonic write version, stamped by the credential coordinator on
* every transition and validated against the read basis — the CAS handle
* that keeps an external writer from being silently overwritten. */
version?: number;
/** Persisted revocation generation, owned by the credential coordinator.
* Logout/removal advances it and leaves the record as a tombstone that
* carries nothing else; every flow captures the generation on its first
* read and every later write verifies it — so a flow raced by a logout in
* ANOTHER process cannot resurrect revoked credentials. Deletion alone
* cannot encode cross-process revocation. */
generation?: number;
/** The MCP server URL these credentials were issued for. Every read path
* refuses (and drops) the record when the configured URL no longer
* matches, so an offline edit of mcp.json cannot replay a token against
* a different endpoint. Absent only on records written before this field
* existed; they bind on their next save. */
serverUrl?: string;
tokens?: StoredOAuthTokens;
clientInformation?: StoredOAuthClientInformation;
/** RFC 9728 / AS metadata discovered on a previous round — including the
* custom resource_metadata URL a 401's WWW-Authenticate advertised, which
* a later interactive login could not re-learn on its own. */
discovery?: OAuthDiscoveryState;
codeVerifier?: string;
/** The exact redirect URL the pending authorization was started with. */
pendingRedirectUrl?: string;
/** The server URL the pending authorization was started against, so the
* token exchange refuses to complete against a URL that changed under it. */
pendingServerUrl?: string;
/** The OAuth state of the pending round, so a restarted app can rebind
* the loopback listener and still verify the browser's callback. */
pendingState?: string;
}
export interface McpOAuthStorage {
get(serverId: string): Promise<McpOAuthRecord | undefined>;
set(serverId: string, record: McpOAuthRecord): Promise<void>;
delete(serverId: string): Promise<void>;
/** Optional atomic read-modify-write. The credential coordinator provides
* it on the storage views it hands to auth flows; base backends may omit
* it (callers fall back to read + set). */
update?(
serverId: string,
apply: (record: McpOAuthRecord) => McpOAuthRecord,
): Promise<McpOAuthRecord>;
/** Optional compare-and-set keyed on the record's version basis
* (`null` asserts absence). Backends over a store with native CAS map it
* through so cross-process writers cannot be clobbered. */
compareAndSet?(
serverId: string,
expectedVersion: number | null,
record: McpOAuthRecord,
): Promise<'committed' | 'conflict' | 'gone'>;
}
export function createMemoryMcpOAuthStorage(): McpOAuthStorage {
const records = new Map<string, McpOAuthRecord>();
return {
async get(serverId) {
const record = records.get(serverId);
return record ? structuredClone(record) : undefined;
},
async set(serverId, record) {
records.set(serverId, structuredClone(record));
},
async delete(serverId) {
records.delete(serverId);
},
};
}
/** Thrown (via the SDK's UnauthorizedError path) when a background connect
* would need the user in a browser. The manager maps it to `needs-auth`. */
export class McpAuthRequiredError extends Error {
constructor(readonly serverId: string) {
super(`MCP server "${serverId}" requires interactive authorization`);
this.name = 'McpAuthRequiredError';
}
}
export interface McpOAuthProviderOptions {
serverId: string;
/** The configured MCP server URL. Credentials are bound to it: a stored
* record whose serverUrl differs is dropped instead of replayed. */
serverUrl: string;
storage: McpOAuthStorage;
config?: McpOAuthConfig;
clientName: string;
clientVersion: string;
/**
* Absent for background connects: the provider then refuses interactive
* redirects with McpAuthRequiredError instead of opening anything.
* Present during a user-initiated login: the redirect URL the loopback
* callback server is listening on, plus a sink that receives the
* authorization URL for the caller to open in the system browser.
*/
interactive?: {
redirectUrl: string;
onAuthorizationUrl(url: URL): void;
/** OAuth `state` for the authorization URL; the callback listener
* verifies the round-trip before accepting a code. */
state?: string;
};
}
/** Stands in for `redirectUrl` on background connects. The SDK reads an
* undefined redirectUrl as "non-interactive grant" and goes straight to the
* token endpoint — before ever consulting the stored refresh token — which
* turns every background connect with a known client into
* "Either provider.prepareTokenRequest() or authorizationCode is required".
* A defined value keeps the SDK on the authorization-code path: refresh
* runs first, and the interactive round it may then want is refused by
* redirectToAuthorization. The URL itself is never opened or sent in a
* token request. */
const BACKGROUND_REDIRECT_URL = 'http://127.0.0.1/maka-mcp-oauth-noninteractive';
export class McpOAuthProvider implements OAuthClientProvider {
/** Present only when an interactive state was supplied — the SDK treats
* a defined method as "client uses state". */
state?: () => string;
constructor(private readonly options: McpOAuthProviderOptions) {
const state = options.interactive?.state;
if (state) this.state = () => state;
}
get redirectUrl(): string {
return this.options.interactive?.redirectUrl ?? BACKGROUND_REDIRECT_URL;
}
get clientMetadata(): OAuthClientMetadata {
return {
client_name: this.options.clientName,
client_uri: 'https://github.com/maka-agent/maka-agent',
software_id: 'maka-desktop',
software_version: this.options.clientVersion,
redirect_uris: this.options.interactive ? [this.options.interactive.redirectUrl] : [],
grant_types: ['authorization_code', 'refresh_token'],
response_types: ['code'],
token_endpoint_auth_method: this.options.config?.clientSecret ? 'client_secret_post' : 'none',
...(this.options.config?.scopes?.length
? { scope: this.options.config.scopes.join(' ') }
: {}),
};
}
async clientInformation(): Promise<StoredOAuthClientInformation | undefined> {
const configured = this.options.config;
if (configured?.clientId) {
return {
client_id: configured.clientId,
...(configured.clientSecret ? { client_secret: configured.clientSecret } : {}),
};
}
const stored = (await this.read()).clientInformation;
// A background connect with no client at all is already decided: the
// interactive round is unavoidable. Refusing here (rather than at the
// redirect) stops the SDK from dynamically registering a throwaway
// client with no usable redirect URI.
if (!stored && !this.options.interactive) {
throw new McpAuthRequiredError(this.options.serverId);
}
return stored;
}
async saveClientInformation(clientInformation: StoredOAuthClientInformation): Promise<void> {
await this.mutate((record) => {
record.clientInformation = clientInformation;
});
}
async tokens(): Promise<StoredOAuthTokens | undefined> {
return (await this.read()).tokens;
}
async saveTokens(tokens: StoredOAuthTokens): Promise<void> {
await this.mutate((record) => {
record.tokens = tokens;
// A fresh token set settles any pending interactive round.
delete record.codeVerifier;
delete record.pendingRedirectUrl;
delete record.pendingServerUrl;
delete record.pendingState;
});
}
async redirectToAuthorization(authorizationUrl: URL): Promise<void> {
const interactive = this.options.interactive;
if (!interactive) throw new McpAuthRequiredError(this.options.serverId);
interactive.onAuthorizationUrl(authorizationUrl);
}
async saveCodeVerifier(codeVerifier: string): Promise<void> {
// A background connect only reaches here on its way to refusing the
// redirect; persisting its verifier would clobber a live interactive
// round's pending record.
if (!this.options.interactive) return;
await this.mutate((record) => {
record.codeVerifier = codeVerifier;
record.pendingRedirectUrl = this.options.interactive?.redirectUrl;
record.pendingServerUrl = this.options.serverUrl;
record.pendingState = this.options.interactive?.state;
});
}
/** Persisted so an interactive login after a background 401 reuses the
* discovery that round already did — including a custom resource_metadata
* URL from WWW-Authenticate that a from-scratch discovery cannot find. */
async discoveryState(): Promise<OAuthDiscoveryState | undefined> {
return (await this.read()).discovery;
}
async saveDiscoveryState(state: OAuthDiscoveryState): Promise<void> {
await this.mutate((record) => {
// A dynamically registered client belongs to the authorization server
// that issued it. When discovery moves the resource to a DIFFERENT
// authorization server, carrying the old registration over would send
// one AS's client credentials (and any secret) to another. Static
// config-supplied clients are unaffected — they never live in the
// record.
const previousIssuer = record.discovery?.authorizationServerUrl;
const nextIssuer = state.authorizationServerUrl;
if (previousIssuer && nextIssuer && `${previousIssuer}` !== `${nextIssuer}`) {
delete record.clientInformation;
delete record.tokens;
}
record.discovery = state;
});
}
async codeVerifier(): Promise<string> {
const value = (await this.read()).codeVerifier;
if (!value) {
throw new Error(`No pending authorization for MCP server "${this.options.serverId}"`);
}
return value;
}
async invalidateCredentials(
scope: 'all' | 'client' | 'tokens' | 'verifier' | 'discovery',
): Promise<void> {
if (scope === 'all') {
await this.options.storage.delete(this.options.serverId);
return;
}
await this.mutate((record) => {
if (scope === 'tokens') delete record.tokens;
if (scope === 'client') delete record.clientInformation;
if (scope === 'discovery') delete record.discovery;
if (scope === 'verifier') {
delete record.codeVerifier;
delete record.pendingRedirectUrl;
delete record.pendingServerUrl;
delete record.pendingState;
}
});
}
/** The redirect URL a pending authorization was started with, so the
* token exchange after the callback reuses the exact registered value. */
async pendingRedirectUrl(): Promise<string | undefined> {
return (await this.read()).pendingRedirectUrl;
}
/** Reads the record, enforcing the endpoint binding: a record issued for
* a different server URL is dropped, never replayed — the config may have
* been edited (even offline) to point the same id at a new endpoint. A
* record carrying credential material with NO binding at all fails closed
* the same way: provenance cannot be established after first use, so a
* legacy or hand-written record is revoked rather than adopted — the user
* logs in again and the fresh record binds on its first save. */
private async read(): Promise<McpOAuthRecord> {
const record = await this.options.storage.get(this.options.serverId);
if (!record) return {};
if (this.bindingMismatch(record)) {
await this.options.storage.delete(this.options.serverId);
return {};
}
return record;
}
private bindingMismatch(record: McpOAuthRecord): boolean {
const boundable =
record.tokens ||
record.clientInformation ||
record.codeVerifier ||
record.discovery ||
record.pendingRedirectUrl ||
record.pendingServerUrl ||
record.pendingState;
return Boolean(boundable) && record.serverUrl !== this.options.serverUrl;
}
/** The same fail-closed binding rule as read(), applied to a mutation
* basis: a record bound elsewhere contributes NOTHING to the new write —
* only the coordinator's bookkeeping survives. Without this, an atomic
* update after an offline endpoint change would carry the old endpoint's
* tokens, client and discovery into the record it re-stamps for the new
* URL — a rebinding read() alone cannot prevent. */
private stripUnbound(record: McpOAuthRecord): McpOAuthRecord {
if (!this.bindingMismatch(record)) return record;
const kept: McpOAuthRecord = {};
if (record.version !== undefined) kept.version = record.version;
if (record.generation !== undefined) kept.generation = record.generation;
return kept;
}
private async mutate(apply: (record: McpOAuthRecord) => void): Promise<void> {
const stamp = (record: McpOAuthRecord): McpOAuthRecord => {
apply(record);
record.serverUrl = this.options.serverUrl;
return record;
};
// The coordinator-provided storage view makes read-apply-write one
// atomic lane operation; plain backends (tests) fall back to two calls.
if (this.options.storage.update) {
await this.options.storage.update(this.options.serverId, (record) =>
stamp(this.stripUnbound({ ...record })),
);
return;
}
const record = await this.read();
await this.options.storage.set(this.options.serverId, stamp(record));
}
}
+291
View File
@@ -0,0 +1,291 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import { formatMcpDiagnosticText } from './diagnostic-text.js';
const X_MCP_HEADER = 'x-mcp-header';
const RFC_9110_TOKEN = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/u;
const UNREACHABLE_SCHEMA_KEYWORDS = [
'items',
'prefixItems',
'contains',
'additionalProperties',
'unevaluatedProperties',
'unevaluatedItems',
'propertyNames',
'patternProperties',
'dependentSchemas',
'oneOf',
'anyOf',
'allOf',
'not',
'if',
'then',
'else',
'$defs',
'definitions',
] as const;
const SCHEMA_MAP_KEYWORDS = new Set([
'patternProperties',
'dependentSchemas',
'$defs',
'definitions',
]);
const WARNING_SAMPLE_LIMIT = 5;
export const MCP_HEADER_WARNING_LENGTH_LIMIT = 512;
export type McpHeaderPrimitiveType = 'string' | 'integer' | 'boolean';
export type McpHeaderDefinitionReasonCode =
| 'not_statically_reachable'
| 'annotation_not_string'
| 'header_name_empty'
| 'header_name_invalid'
| 'property_type_unsupported'
| 'header_name_duplicate';
export interface McpHeaderDeclaration {
readonly path: readonly string[];
readonly headerName: string;
readonly type: McpHeaderPrimitiveType;
}
export interface McpHeaderDefinitionIssue {
readonly code: McpHeaderDefinitionReasonCode;
readonly path: readonly string[];
}
export type McpHeaderDefinitionValidation =
| {
readonly valid: true;
readonly declarations: readonly McpHeaderDeclaration[];
}
| {
readonly valid: false;
readonly issue: McpHeaderDefinitionIssue;
};
export interface McpHeaderToolDefinitionLike {
readonly name: string;
readonly inputSchema: unknown;
}
export interface ValidMcpHeaderTool<T extends McpHeaderToolDefinitionLike> {
readonly tool: T;
readonly declarations: readonly McpHeaderDeclaration[];
}
export interface McpHeaderToolRejection {
readonly toolName: string;
readonly issue: McpHeaderDefinitionIssue;
}
export interface McpHeaderToolPartition<T extends McpHeaderToolDefinitionLike> {
readonly valid: readonly ValidMcpHeaderTool<T>[];
readonly rejected: readonly McpHeaderToolRejection[];
}
export type McpHeaderArgumentValidation =
| { readonly valid: true }
| {
readonly valid: false;
readonly code: 'unsafe_integer_argument';
readonly path: readonly string[];
};
/**
* Validate the narrow SEP-2243 schema extension without becoming a general
* JSON Schema evaluator. A declaration is reachable only through `properties`
* keys; finding one in a dynamic or composed subschema invalidates the Tool.
*/
export function validateMcpHeaderDefinition(inputSchema: unknown): McpHeaderDefinitionValidation {
const declarations: McpHeaderDeclaration[] = [];
const headerPaths = new Map<string, readonly string[]>();
const visit = (
value: unknown,
path: readonly string[],
staticallyReachable: boolean,
): McpHeaderDefinitionIssue | undefined => {
if (!isRecord(value)) return undefined;
if (X_MCP_HEADER in value) {
if (!staticallyReachable || path.length === 0) {
return { code: 'not_statically_reachable', path };
}
const headerName = value[X_MCP_HEADER];
if (typeof headerName !== 'string') {
return { code: 'annotation_not_string', path };
}
if (headerName.length === 0) {
return { code: 'header_name_empty', path };
}
if (!RFC_9110_TOKEN.test(headerName)) {
return { code: 'header_name_invalid', path };
}
const type = value.type;
if (!isMcpHeaderPrimitiveType(type)) {
return { code: 'property_type_unsupported', path };
}
const normalizedHeaderName = headerName.toLowerCase();
if (headerPaths.has(normalizedHeaderName)) {
return { code: 'header_name_duplicate', path };
}
headerPaths.set(normalizedHeaderName, path);
declarations.push({ path, headerName, type });
}
if (isRecord(value.properties)) {
for (const [propertyName, propertySchema] of Object.entries(value.properties)) {
const issue = visit(propertySchema, [...path, propertyName], staticallyReachable);
if (issue) return issue;
}
}
for (const keyword of UNREACHABLE_SCHEMA_KEYWORDS) {
const subschema = value[keyword];
if (subschema === undefined) continue;
const branches =
Array.isArray(subschema) || !SCHEMA_MAP_KEYWORDS.has(keyword) || !isRecord(subschema)
? asArray(subschema)
: Object.values(subschema);
for (const branch of branches) {
const issue = visit(branch, [...path, `<${keyword}>`], false);
if (issue) return issue;
}
}
return undefined;
};
const issue = visit(inputSchema, [], true);
return issue ? { valid: false, issue } : { valid: true, declarations };
}
/**
* Partition independently so one malformed server Tool cannot hide valid
* siblings. The returned Tool references are unchanged.
*/
export function partitionMcpHeaderToolDefinitions<T extends McpHeaderToolDefinitionLike>(
tools: readonly T[],
): McpHeaderToolPartition<T> {
const valid: ValidMcpHeaderTool<T>[] = [];
const rejected: McpHeaderToolRejection[] = [];
for (const tool of tools) {
const validation = validateMcpHeaderDefinition(tool.inputSchema);
if (validation.valid) {
valid.push({ tool, declarations: validation.declarations });
} else {
rejected.push({ toolName: tool.name, issue: validation.issue });
}
}
return { valid, rejected };
}
/**
* Produce one log-safe diagnostic per refresh. It exposes stable reason codes,
* never raw schemas or arguments, and remains bounded even for hostile names.
*/
export function formatMcpHeaderExclusionWarning(
rejections: readonly McpHeaderToolRejection[],
): string | undefined {
if (rejections.length === 0) return undefined;
const candidates = rejections
.slice(0, WARNING_SAMPLE_LIMIT)
.map(
({ toolName, issue }) =>
`${JSON.stringify(formatMcpDiagnosticText(toolName))} [${issue.code}]`,
);
const prefix =
`MCP tool discovery excluded ${rejections.length} Tool definition(s) with invalid ` +
'x-mcp-header annotations';
// Reserve room for the omitted count and prefer fewer complete samples over
// slicing through a Tool name or stable reason code.
for (let sampleCount = candidates.length; sampleCount >= 0; sampleCount -= 1) {
const omitted = rejections.length - sampleCount;
const sample = candidates.slice(0, sampleCount).join(', ');
const detail = sample ? `: ${sample}` : '';
const suffix = omitted > 0 ? `; ${omitted} more not shown` : '';
const warning = `${prefix}${detail}${suffix}`;
if (warning.length <= MCP_HEADER_WARNING_LENGTH_LIMIT) return warning;
}
return truncateRenderedWarning(prefix);
}
/**
* Enforce the SEP-2243 safe-integer rule after arguments exist but before the
* caller enters the HTTP transport.
*/
export function validateMcpHeaderArguments(
declarations: readonly McpHeaderDeclaration[],
args: Readonly<Record<string, unknown>>,
): McpHeaderArgumentValidation {
for (const declaration of declarations) {
if (declaration.type !== 'integer') continue;
const value = valueAtPath(args, declaration.path);
if (value === undefined || value === null) continue;
if (typeof value === 'number' && Number.isInteger(value) && !Number.isSafeInteger(value)) {
return {
valid: false,
code: 'unsafe_integer_argument',
path: declaration.path,
};
}
}
return { valid: true };
}
function isMcpHeaderPrimitiveType(value: unknown): value is McpHeaderPrimitiveType {
return value === 'string' || value === 'integer' || value === 'boolean';
}
function asArray(value: unknown): readonly unknown[] {
return Array.isArray(value) ? value : [value];
}
function valueAtPath(root: unknown, path: readonly string[]): unknown {
let value = root;
for (const segment of path) {
if (!isRecord(value)) return undefined;
value = value[segment];
}
return value;
}
function truncateRenderedWarning(value: string): string {
if (value.length <= MCP_HEADER_WARNING_LENGTH_LIMIT) return value;
const end = MCP_HEADER_WARNING_LENGTH_LIMIT - 1;
const safeEnd = end > 0 && /[\uD800-\uDBFF]/u.test(value[end - 1] ?? '') ? end - 1 : end;
return `${value.slice(0, safeEnd)}\u2026`;
}
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value);
}
+90
View File
@@ -0,0 +1,90 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import { createHash } from 'node:crypto';
import type { McpToolBinding } from '@maka/core/mcp';
const MCP_TOOL_BINDING_PREFIX = 'mcpb1.';
const MAX_MCP_TOOL_BINDING_CHARS = 96;
export interface McpToolBindingIdentity {
managerId: string;
connectionGeneration: number;
serverId: string;
toolName: string;
definitionFingerprint: string;
}
export interface McpParsedToolBinding {
managerId: string;
connectionGeneration: number;
}
export function createMcpToolBinding(identity: McpToolBindingIdentity): McpToolBinding {
if (!isValidIdentity(identity)) throw new Error('Invalid MCP tool binding identity');
const generation = identity.connectionGeneration.toString(36);
const digest = createHash('sha256')
.update(
JSON.stringify([
identity.managerId,
identity.connectionGeneration,
identity.serverId,
identity.toolName,
identity.definitionFingerprint,
]),
)
.digest('base64url');
return `${MCP_TOOL_BINDING_PREFIX}${identity.managerId}.${generation}.${digest}` as McpToolBinding;
}
export function parseMcpToolBinding(binding: unknown): McpParsedToolBinding | undefined {
if (
typeof binding !== 'string' ||
binding.length > MAX_MCP_TOOL_BINDING_CHARS ||
!binding.startsWith(MCP_TOOL_BINDING_PREFIX)
) {
return undefined;
}
const match = /^mcpb1\.([A-Za-z0-9_-]{22})\.([1-9a-z][0-9a-z]*)\.([A-Za-z0-9_-]{43})$/u.exec(
binding,
);
if (!match) return undefined;
const connectionGeneration = Number.parseInt(match[2], 36);
if (
!Number.isSafeInteger(connectionGeneration) ||
connectionGeneration <= 0 ||
connectionGeneration.toString(36) !== match[2]
) {
return undefined;
}
return { managerId: match[1], connectionGeneration };
}
function isValidIdentity(identity: McpToolBindingIdentity): boolean {
return (
typeof identity.managerId === 'string' &&
/^[A-Za-z0-9_-]{22}$/u.test(identity.managerId) &&
Number.isSafeInteger(identity.connectionGeneration) &&
identity.connectionGeneration > 0 &&
typeof identity.serverId === 'string' &&
typeof identity.toolName === 'string' &&
typeof identity.definitionFingerprint === 'string' &&
/^[A-Za-z0-9_-]{43}$/u.test(identity.definitionFingerprint)
);
}
+99
View File
@@ -0,0 +1,99 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import { ProtocolError, SdkError, SdkErrorCode } from '@modelcontextprotocol/client';
import { formatMcpDiagnosticText, MCP_ERROR_DIAGNOSTIC_CODE_POINTS } from './diagnostic-text.js';
export class McpToolCallError extends Error {
readonly serverId: string;
readonly toolName: string;
constructor(serverId: string, toolName: string, message: string, options?: ErrorOptions) {
super(
`MCP ${formatMcpDiagnosticText(serverId)}/${formatMcpDiagnosticText(
toolName,
)}: ${formatMcpDiagnosticText(message, MCP_ERROR_DIAGNOSTIC_CODE_POINTS)}`,
options,
);
this.name = 'McpToolCallError';
this.serverId = serverId;
this.toolName = toolName;
}
}
export function normalizeToolCallError(
serverId: string,
toolName: string,
error: unknown,
signal?: AbortSignal,
): Error {
if (error instanceof McpToolCallError) return error;
if (signal?.aborted) {
return new McpToolCallError(serverId, toolName, 'tool call aborted', { cause: error });
}
if (error instanceof SdkError) {
switch (error.code) {
case SdkErrorCode.RequestTimeout:
return new McpToolCallError(serverId, toolName, 'tool call timed out', { cause: error });
case SdkErrorCode.InvalidResult:
if (isLegacyDeferredToolResultError(error)) {
return new McpToolCallError(
serverId,
toolName,
'server returned an unsupported deferred tool result',
{ cause: error },
);
}
return new McpToolCallError(serverId, toolName, 'server returned an invalid tool result', {
cause: error,
});
case SdkErrorCode.UnsupportedResultType:
return new McpToolCallError(
serverId,
toolName,
'server returned an unsupported deferred tool result',
{ cause: error },
);
default:
return new McpToolCallError(serverId, toolName, 'tool call failed', { cause: error });
}
}
if (error instanceof ProtocolError) {
return new McpToolCallError(
serverId,
toolName,
'server rejected the tool call or returned an invalid result',
{ cause: error },
);
}
return new McpToolCallError(serverId, toolName, 'tool call failed', { cause: error });
}
/**
* SDK v2 rejects 2026-era result-family markers on a legacy connection at
* its wire-schema boundary. Those responses never reach callTool(), so map
* the pinned SDK's fixed validation diagnostic to Maka's deferred-result
* boundary alongside UnsupportedResultType.
*/
function isLegacyDeferredToolResultError(error: SdkError): boolean {
if (!error.message.startsWith('Invalid result for tools/call:')) return false;
return ["'task'", "'inputRequests'", "'requestState'"].some((marker) =>
error.message.includes(`body carries ${marker}`),
);
}
+85
View File
@@ -0,0 +1,85 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import { createHash } from 'node:crypto';
import type { Tool } from '@modelcontextprotocol/client';
const MAX_TOOL_DEFINITION_DEPTH = 100;
const MAX_TOOL_DEFINITION_NODES = 100_000;
const MAX_TOOL_DEFINITION_BYTES = 1_048_576;
export interface McpToolDefinitionFingerprint {
value: string;
bytes: number;
}
export function fingerprintMcpToolDefinition(tool: Tool): McpToolDefinitionFingerprint {
const state = { nodes: 0, scalarBytes: 0 };
const canonical = JSON.stringify(canonicalizeToolValue(tool, state, 0));
const bytes = Buffer.byteLength(canonical);
if (bytes > MAX_TOOL_DEFINITION_BYTES) {
throw new Error(`MCP tool definition exceeds ${MAX_TOOL_DEFINITION_BYTES} bytes`);
}
return {
value: createHash('sha256').update(canonical).digest('base64url'),
bytes,
};
}
function canonicalizeToolValue(
value: unknown,
state: { nodes: number; scalarBytes: number },
depth: number,
): unknown {
state.nodes += 1;
if (state.nodes > MAX_TOOL_DEFINITION_NODES) {
throw new Error(`MCP tool definition exceeds ${MAX_TOOL_DEFINITION_NODES} values`);
}
if (depth > MAX_TOOL_DEFINITION_DEPTH) {
throw new Error(`MCP tool definition exceeds depth ${MAX_TOOL_DEFINITION_DEPTH}`);
}
if (typeof value === 'string') {
state.scalarBytes += Buffer.byteLength(value);
assertToolDefinitionBytes(state.scalarBytes);
return value;
}
if (Array.isArray(value)) {
return value.map((item) => canonicalizeToolValue(item, state, depth + 1));
}
if (!isRecord(value)) return value;
return Object.fromEntries(
Object.keys(value)
.sort()
.map((key) => {
state.scalarBytes += Buffer.byteLength(key);
assertToolDefinitionBytes(state.scalarBytes);
return [key, canonicalizeToolValue(value[key], state, depth + 1)];
}),
);
}
function assertToolDefinitionBytes(bytes: number): void {
if (bytes > MAX_TOOL_DEFINITION_BYTES) {
throw new Error(`MCP tool definition exceeds ${MAX_TOOL_DEFINITION_BYTES} bytes`);
}
}
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value);
}
+104
View File
@@ -0,0 +1,104 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import type { Tool } from '@modelcontextprotocol/client';
import { formatMcpDiagnosticText } from './diagnostic-text.js';
import { fingerprintMcpToolDefinition } from './tool-definition.js';
export const DEFAULT_TOOL_DISCOVERY_LIMITS = {
maxPages: 1_000,
maxTools: 1_000,
maxDefinitionBytes: 16 * 1_048_576,
} as const;
export interface McpToolPage {
readonly tools: readonly Tool[];
readonly nextCursor?: string;
}
export interface McpToolPageSource {
requestToolsPage(cursor: string | undefined, timeoutMs: number): Promise<McpToolPage>;
}
export interface McpToolDiscoveryLimits {
readonly maxPages: number;
readonly maxTools: number;
readonly maxDefinitionBytes: number;
}
export interface McpDiscoveredTool {
readonly definition: Tool;
readonly definitionFingerprint: string;
}
/**
* Walk tools/list without delegating aggregation or cache ownership to the SDK.
*
* Cursors are opaque: an empty string is a continuation, and only undefined
* terminates the walk.
*/
export async function discoverMcpTools(
source: McpToolPageSource,
serverId: string,
timeoutMs: number,
limits: McpToolDiscoveryLimits = DEFAULT_TOOL_DISCOVERY_LIMITS,
): Promise<McpDiscoveredTool[]> {
const result: McpDiscoveredTool[] = [];
const seenCursors = new Set<string>();
const seenNames = new Set<string>();
let definitionBytes = 0;
let cursor: string | undefined;
for (let page = 0; page < limits.maxPages; page += 1) {
const response = await source.requestToolsPage(cursor, timeoutMs);
for (const tool of response.tools) {
if (result.length >= limits.maxTools) {
throw new Error(`MCP server "${serverId}" exceeded ${limits.maxTools} tools`);
}
if (seenNames.has(tool.name)) {
throw new Error(
`MCP server "${serverId}" returned duplicate tool ${JSON.stringify(
formatMcpDiagnosticText(tool.name),
)}`,
);
}
seenNames.add(tool.name);
const fingerprint = fingerprintMcpToolDefinition(tool);
definitionBytes += fingerprint.bytes;
if (definitionBytes > limits.maxDefinitionBytes) {
throw new Error(
`MCP server "${serverId}" exceeded ${limits.maxDefinitionBytes} tool definition bytes`,
);
}
result.push({
definition: structuredClone(tool),
definitionFingerprint: fingerprint.value,
});
}
if (response.nextCursor === undefined) return result;
if (seenCursors.has(response.nextCursor)) {
throw new Error(`MCP server "${serverId}" repeated a tools cursor`);
}
seenCursors.add(response.nextCursor);
cursor = response.nextCursor;
}
throw new Error(`MCP server "${serverId}" exceeded ${limits.maxPages} tool pages`);
}
@@ -0,0 +1,57 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import type { JsonSchemaValidator, Tool } from '@modelcontextprotocol/client';
import { AjvJsonSchemaValidator } from '@modelcontextprotocol/client/validators/ajv';
export interface McpToolCallPreparation {
readonly definitionForSdk: Tool;
readonly validateOutput?: JsonSchemaValidator<unknown>;
}
export type McpToolCallPreparationState =
| { readonly ok: true; readonly value: McpToolCallPreparation }
| { readonly ok: false; readonly cause: unknown };
/**
* Keep the SDK's SEP-2243 input-definition view while moving output validation
* behind Maka's deferred-result classification. Preparation is cached by the
* manager's immutable Tool snapshot and always happens before the wire call.
*/
export class McpToolCallPreparer {
prepare(definition: Tool): McpToolCallPreparationState {
try {
const definitionForSdk = structuredClone(definition);
delete definitionForSdk.outputSchema;
if (definition.outputSchema === undefined) {
return { ok: true, value: { definitionForSdk } };
}
// `$id` is schema-local identity. Reusing one SDK validator cache would
// let two independently advertised Tools share the first schema
// registered under the same `$id`, whichever server connected first.
// Compile per preparation so each published Tool owns its validator.
const validateOutput = new AjvJsonSchemaValidator().getValidator<unknown>(
structuredClone(definition.outputSchema),
);
return { ok: true, value: { definitionForSdk, validateOutput } };
} catch (cause) {
return { ok: false, cause };
}
}
}
+90
View File
@@ -0,0 +1,90 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
// packages/mcp/src/transport-security.ts
//
// Transport security is not network authority: cleartext-loopback is a
// TRUST decision, not a scheme rule, and only the user's own configuration
// confers it. A remotely supplied destination — a redirect Location, an
// OAuth metadata URL, an authorization endpoint — must not inherit the
// loopback exception unless the user pointed the server itself at loopback
// (a local trust root).
//
// The same provenance rule extends to `https` aimed BACK INTO the user's
// machine or network: a remote server's metadata can name
// `https://169.254.169.254/…` or `https://192.168.1.1/…` and the client
// would dutifully issue the request — blind SSRF from inside the network.
// Public https destinations pass (that is what OAuth endpoints look like);
// loopback and private-range IP LITERALS require the configured endpoint to
// be a matching local/internal trust root. Names that merely RESOLVE to
// private addresses are accepted risk: checking them would require a
// resolve here and could still re-resolve differently at request time.
import { isLoopbackHost, isNonLoopbackCleartextHttp, isPrivateRangeHost } from '@maka/core/mcp';
export interface UrlProvenance {
configuredOrigin: string;
configuredOriginIsLoopback: boolean;
configuredOriginIsPrivate: boolean;
}
export function urlProvenance(configuredServerUrl: URL): UrlProvenance {
return {
configuredOrigin: configuredServerUrl.origin,
configuredOriginIsLoopback: isLoopbackHost(configuredServerUrl.hostname),
configuredOriginIsPrivate: isPrivateRangeHost(configuredServerUrl.hostname),
};
}
export function assertTransportSecurity(url: URL, provenance: UrlProvenance): void {
if (url.protocol !== 'http:' && url.protocol !== 'https:') {
throw new Error(`refused non-HTTP request to ${url.protocol}//`);
}
if (url.protocol === 'https:') {
if (url.origin === provenance.configuredOrigin) return;
if (isLoopbackHost(url.hostname)) {
if (provenance.configuredOriginIsLoopback) return;
throw new Error(
`refused remotely supplied loopback https destination ${url.origin}: ` +
'only a user-configured loopback endpoint may target the local machine',
);
}
if (isPrivateRangeHost(url.hostname)) {
if (provenance.configuredOriginIsLoopback || provenance.configuredOriginIsPrivate) return;
throw new Error(
`refused remotely supplied private-range https destination ${url.origin}: ` +
'only a local or internal configured endpoint may target the private network',
);
}
return;
}
if (isNonLoopbackCleartextHttp(url)) {
throw new Error(
`refused cleartext http request to ${url.origin}: non-loopback hosts require https`,
);
}
// http + loopback from here on: allowed for the configured endpoint
// itself, or when the configured endpoint is a loopback trust root.
if (url.origin === provenance.configuredOrigin) return;
if (provenance.configuredOriginIsLoopback) return;
throw new Error(
`refused remotely supplied loopback http destination ${url.origin}: ` +
'only a user-configured loopback endpoint may use cleartext',
);
}
+10
View File
@@ -0,0 +1,10 @@
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"outDir": "./dist",
"rootDir": "./src",
"composite": true
},
"include": ["src/**/*.ts"],
"references": [{ "path": "../core" }]
}