@fitchmultz/pi-mcp-adapter 6.0.0 → 7.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +33 -0
- package/OAUTH.md +1 -1
- package/README.md +27 -18
- package/dist/app-bridge.bundle.js +14 -14
- package/dist/config.js +41 -16
- package/dist/direct-tools.js +1 -1
- package/dist/gateway-arguments.d.ts +1 -1
- package/dist/index.js +38 -59
- package/dist/lifecycle.d.ts +2 -2
- package/dist/lifecycle.js +2 -2
- package/dist/mcp-auth-flow.js +2 -2
- package/dist/mcp-auth.d.ts +1 -1
- package/dist/mcp-auth.js +3 -3
- package/dist/mcp-code.d.ts +6 -6
- package/dist/mcp-code.js +11 -10
- package/dist/mcp-oauth-provider.d.ts +5 -5
- package/dist/mcp-oauth-provider.js +5 -5
- package/dist/mcp-output-guard.d.ts +1 -1
- package/dist/mcp-output-guard.js +1 -1
- package/dist/mcp-panel.d.ts +2 -2
- package/dist/mcp-panel.js +2 -2
- package/dist/mcp-setup-panel.d.ts +5 -4
- package/dist/mcp-setup-panel.js +15 -7
- package/dist/mcp-trace.d.ts +1 -1
- package/dist/mcp-trace.js +1 -1
- package/dist/npx-resolver.js +8 -4
- package/dist/proxy-modes.d.ts +2 -2
- package/dist/proxy-modes.js +20 -19
- package/dist/sampling-handler.js +1 -0
- package/dist/search-ranking.js +6 -2
- package/dist/server-manager.d.ts +2 -2
- package/dist/server-manager.js +44 -27
- package/dist/session-recovery.d.ts +7 -4
- package/dist/session-recovery.js +76 -10
- package/dist/tool-loader.d.ts +7 -2
- package/dist/tool-loader.js +56 -5
- package/dist/tool-metadata.d.ts +43 -43
- package/dist/tool-result-renderer.d.ts +3 -3
- package/dist/tool-result-renderer.js +3 -3
- package/dist/ui-resource-handler.d.ts +2 -2
- package/dist/ui-resource-handler.js +2 -2
- package/dist/ui-server.js +5 -4
- package/dist/ui-stream-types.d.ts +8 -8
- package/dist/unix-socket-transport.d.ts +1 -1
- package/dist/unix-socket-transport.js +1 -1
- package/dist/utils.d.ts +1 -0
- package/dist/utils.js +14 -0
- package/package.json +34 -98
- package/skills/mcp-scripting/SKILL.md +2 -0
- package/abort.ts +0 -34
- package/agent-dir.ts +0 -24
- package/app-bridge.bundle.js +0 -109
- package/banner.png +0 -0
- package/checkpoint.ts +0 -55
- package/commands.ts +0 -622
- package/config.ts +0 -1204
- package/consent-manager.ts +0 -25
- package/direct-tools.ts +0 -75
- package/elicitation-handler.ts +0 -349
- package/error-signal.ts +0 -21
- package/gateway-arguments.ts +0 -73
- package/glimpse-ui.ts +0 -80
- package/host-html-template.ts +0 -456
- package/index.ts +0 -767
- package/init.ts +0 -613
- package/legacy-migration.ts +0 -47
- package/lifecycle.ts +0 -165
- package/logger.ts +0 -127
- package/mcp-auth-flow.ts +0 -975
- package/mcp-auth.ts +0 -793
- package/mcp-callback-server.ts +0 -450
- package/mcp-code.ts +0 -412
- package/mcp-keyring-helper.cjs +0 -89
- package/mcp-oauth-provider.ts +0 -774
- package/mcp-output-guard.ts +0 -530
- package/mcp-panel.ts +0 -907
- package/mcp-script-worker.mjs +0 -131
- package/mcp-setup-panel.ts +0 -666
- package/mcp-status.ts +0 -110
- package/mcp-trace.ts +0 -295
- package/metadata-cache.ts +0 -271
- package/npx-resolver.ts +0 -488
- package/onboarding-state.ts +0 -58
- package/panel-keys.ts +0 -37
- package/prompts.ts +0 -337
- package/proxy-modes.ts +0 -1109
- package/resource-tools.ts +0 -52
- package/runtime-owner.ts +0 -123
- package/sampling-handler.ts +0 -276
- package/scripts/build-app-bridge.mjs +0 -15
- package/scripts/build.mjs +0 -132
- package/scripts/prepare.mjs +0 -103
- package/search-ranking.ts +0 -132
- package/server-manager.ts +0 -1320
- package/session-recovery.ts +0 -316
- package/state.ts +0 -64
- package/tool-approval.ts +0 -78
- package/tool-loader.ts +0 -153
- package/tool-metadata.ts +0 -240
- package/tool-registrar.ts +0 -74
- package/tool-result-renderer.ts +0 -294
- package/tsconfig.build.json +0 -13
- package/tsconfig.json +0 -16
- package/types.ts +0 -785
- package/ui-resource-handler.ts +0 -249
- package/ui-server.ts +0 -808
- package/ui-session.ts +0 -568
- package/ui-stream-types.ts +0 -89
- package/ui-tool-visibility.ts +0 -25
- package/unix-socket-transport.ts +0 -85
- package/utils.ts +0 -307
package/mcp-status.ts
DELETED
|
@@ -1,110 +0,0 @@
|
|
|
1
|
-
import type { McpExtensionState } from "./state.ts";
|
|
2
|
-
import {
|
|
3
|
-
MCP_STATUS_EVENT,
|
|
4
|
-
MCP_STATUS_SNAPSHOT_VERSION,
|
|
5
|
-
type McpServerStatusSnapshot,
|
|
6
|
-
type McpStatusSnapshot,
|
|
7
|
-
} from "./types.ts";
|
|
8
|
-
|
|
9
|
-
const FAILURE_BACKOFF_MS = 60 * 1000;
|
|
10
|
-
|
|
11
|
-
export interface McpStatusEventBus {
|
|
12
|
-
emit(channel: string, data: unknown): void;
|
|
13
|
-
}
|
|
14
|
-
|
|
15
|
-
function getActiveFailureAgeSeconds(state: McpExtensionState, serverName: string): number | undefined {
|
|
16
|
-
const failedAt = state.failureTracker.get(serverName);
|
|
17
|
-
if (!failedAt) return undefined;
|
|
18
|
-
const ageMs = Date.now() - failedAt;
|
|
19
|
-
if (ageMs > FAILURE_BACKOFF_MS) return undefined;
|
|
20
|
-
return Math.round(ageMs / 1000);
|
|
21
|
-
}
|
|
22
|
-
|
|
23
|
-
/** Build a sanitized snapshot without connecting or querying any MCP server. */
|
|
24
|
-
export function createMcpStatusSnapshot(state: McpExtensionState): McpStatusSnapshot {
|
|
25
|
-
const servers: McpServerStatusSnapshot[] = [];
|
|
26
|
-
let totalTools = 0;
|
|
27
|
-
let totalResources = 0;
|
|
28
|
-
let connectedCount = 0;
|
|
29
|
-
let disabledCount = 0;
|
|
30
|
-
|
|
31
|
-
for (const name of Object.keys(state.config.mcpServers)) {
|
|
32
|
-
const definition = state.config.mcpServers[name];
|
|
33
|
-
const disabled = definition?.disabled === true;
|
|
34
|
-
const connection = disabled ? undefined : state.manager.getConnection(name);
|
|
35
|
-
const metadata = disabled ? undefined : state.toolMetadata.get(name);
|
|
36
|
-
const toolCount = metadata?.filter(tool => !tool.resourceUri).length ?? (connection?.status === "connected" ? connection.tools.length : 0);
|
|
37
|
-
const resourceCount = disabled
|
|
38
|
-
? undefined
|
|
39
|
-
: state.resourceCounts?.get(name) ?? (connection?.status === "connected" ? connection.resources.length : undefined);
|
|
40
|
-
const failedAgoSeconds = disabled ? undefined : getActiveFailureAgeSeconds(state, name);
|
|
41
|
-
|
|
42
|
-
let status: McpServerStatusSnapshot["status"] = "not-connected";
|
|
43
|
-
if (disabled) {
|
|
44
|
-
status = "disabled";
|
|
45
|
-
disabledCount++;
|
|
46
|
-
} else if (connection?.status === "connected") {
|
|
47
|
-
status = "connected";
|
|
48
|
-
connectedCount++;
|
|
49
|
-
} else if (connection?.status === "needs-auth") {
|
|
50
|
-
status = "needs-auth";
|
|
51
|
-
} else if (failedAgoSeconds !== undefined) {
|
|
52
|
-
status = "failed";
|
|
53
|
-
} else if (metadata !== undefined) {
|
|
54
|
-
status = "cached";
|
|
55
|
-
}
|
|
56
|
-
|
|
57
|
-
totalTools += disabled ? 0 : toolCount;
|
|
58
|
-
if (!disabled && resourceCount !== undefined) totalResources += resourceCount;
|
|
59
|
-
servers.push({
|
|
60
|
-
name,
|
|
61
|
-
status,
|
|
62
|
-
toolCount,
|
|
63
|
-
catalogKnown: metadata !== undefined || connection?.status === "connected",
|
|
64
|
-
...(resourceCount !== undefined ? { resourceCount } : {}),
|
|
65
|
-
...(status === "failed" && failedAgoSeconds !== undefined ? { failedAgoSeconds } : {}),
|
|
66
|
-
disabled,
|
|
67
|
-
});
|
|
68
|
-
}
|
|
69
|
-
|
|
70
|
-
return {
|
|
71
|
-
version: MCP_STATUS_SNAPSHOT_VERSION,
|
|
72
|
-
servers,
|
|
73
|
-
totalTools,
|
|
74
|
-
totalResources,
|
|
75
|
-
connectedCount,
|
|
76
|
-
disabledCount,
|
|
77
|
-
};
|
|
78
|
-
}
|
|
79
|
-
|
|
80
|
-
export function publishMcpStatusSnapshot(
|
|
81
|
-
state: McpExtensionState,
|
|
82
|
-
snapshot?: McpStatusSnapshot,
|
|
83
|
-
): void {
|
|
84
|
-
const events = state.statusEvents;
|
|
85
|
-
if (!events) return;
|
|
86
|
-
try {
|
|
87
|
-
events.emit(MCP_STATUS_EVENT, snapshot ?? createMcpStatusSnapshot(state));
|
|
88
|
-
} catch {
|
|
89
|
-
// Event consumers must not be able to interrupt MCP operations.
|
|
90
|
-
}
|
|
91
|
-
}
|
|
92
|
-
|
|
93
|
-
export function publishMcpStatusShutdown(events: McpStatusEventBus | undefined): void {
|
|
94
|
-
if (!events) return;
|
|
95
|
-
try {
|
|
96
|
-
events.emit(MCP_STATUS_EVENT, {
|
|
97
|
-
version: MCP_STATUS_SNAPSHOT_VERSION,
|
|
98
|
-
servers: [],
|
|
99
|
-
totalTools: 0,
|
|
100
|
-
totalResources: 0,
|
|
101
|
-
connectedCount: 0,
|
|
102
|
-
disabledCount: 0,
|
|
103
|
-
} satisfies McpStatusSnapshot);
|
|
104
|
-
} catch {
|
|
105
|
-
// Event consumers must not be able to interrupt MCP shutdown.
|
|
106
|
-
}
|
|
107
|
-
}
|
|
108
|
-
|
|
109
|
-
export type { McpServerStatusSnapshot, McpStatusSnapshot } from "./types.ts";
|
|
110
|
-
export { MCP_STATUS_EVENT, MCP_STATUS_SNAPSHOT_VERSION } from "./types.ts";
|
package/mcp-trace.ts
DELETED
|
@@ -1,295 +0,0 @@
|
|
|
1
|
-
import { appendFile, mkdir, writeFile } from "node:fs/promises";
|
|
2
|
-
import { Buffer } from "node:buffer";
|
|
3
|
-
import { dirname, isAbsolute, resolve } from "node:path";
|
|
4
|
-
import type { Transport } from "@modelcontextprotocol/client";
|
|
5
|
-
import type { JSONRPCMessage, MessageExtraInfo } from "@modelcontextprotocol/client";
|
|
6
|
-
|
|
7
|
-
export const MCP_TRACE_SCHEMA_VERSION = 1;
|
|
8
|
-
export const DEFAULT_MCP_TRACE_MAX_BYTES = 256 * 1024;
|
|
9
|
-
export const DEFAULT_MCP_TRACE_MAX_EVENTS = 10_000;
|
|
10
|
-
|
|
11
|
-
export type McpTraceDirection = "outbound" | "inbound";
|
|
12
|
-
export type McpTraceTransport = "stdio" | "unix-socket" | "sse" | "streamable-http" | "unknown";
|
|
13
|
-
export type McpTraceMessageKind = "request" | "response" | "notification";
|
|
14
|
-
|
|
15
|
-
export interface McpTraceSettings {
|
|
16
|
-
/** Enable metadata-only protocol tracing for all servers unless overridden. */
|
|
17
|
-
enabled?: boolean;
|
|
18
|
-
/** JSONL destination. Relative paths are resolved from the session cwd. */
|
|
19
|
-
file?: string;
|
|
20
|
-
/** Maximum bytes retained in the per-session JSONL file. */
|
|
21
|
-
maxBytes?: number;
|
|
22
|
-
/** Maximum events retained in the per-session JSONL file. */
|
|
23
|
-
maxEvents?: number;
|
|
24
|
-
}
|
|
25
|
-
|
|
26
|
-
export interface McpTraceEvent {
|
|
27
|
-
version: typeof MCP_TRACE_SCHEMA_VERSION;
|
|
28
|
-
timestamp: string;
|
|
29
|
-
direction: McpTraceDirection;
|
|
30
|
-
server: string;
|
|
31
|
-
transport: McpTraceTransport;
|
|
32
|
-
kind: McpTraceMessageKind;
|
|
33
|
-
status: "sent" | "received" | "error";
|
|
34
|
-
method?: string;
|
|
35
|
-
id?: string | number | null;
|
|
36
|
-
relatedRequestId?: string | number;
|
|
37
|
-
errorCode?: number | string;
|
|
38
|
-
bytes?: number;
|
|
39
|
-
durationMs?: number;
|
|
40
|
-
}
|
|
41
|
-
|
|
42
|
-
export interface McpTraceWriterOptions {
|
|
43
|
-
filePath: string;
|
|
44
|
-
maxBytes?: number;
|
|
45
|
-
maxEvents?: number;
|
|
46
|
-
appendFile?: (path: string, data: string, options: { encoding: "utf8" }) => Promise<void>;
|
|
47
|
-
writeFile?: (path: string, data: string, options: { encoding: "utf8" }) => Promise<void>;
|
|
48
|
-
mkdir?: (path: string, options: { recursive: true }) => Promise<string | undefined>;
|
|
49
|
-
}
|
|
50
|
-
|
|
51
|
-
function boundedPositiveInteger(value: number | undefined, fallback: number): number {
|
|
52
|
-
if (!Number.isFinite(value) || value === undefined || value <= 0) return fallback;
|
|
53
|
-
return Math.floor(value);
|
|
54
|
-
}
|
|
55
|
-
|
|
56
|
-
/** Redact strings before they can become durable trace metadata. */
|
|
57
|
-
export function redactTraceText(value: string, maxLength = 160): string {
|
|
58
|
-
if (/\b(?:token|secret|password|passwd|api[_-]?key|authorization|cookie)\b/i.test(value)) {
|
|
59
|
-
return "[REDACTED]";
|
|
60
|
-
}
|
|
61
|
-
let redacted = value
|
|
62
|
-
.replace(/\b[a-z][a-z\d+.-]*:\/\/[^\s"'<>]+/gi, "[REDACTED_URL]")
|
|
63
|
-
.replace(/\b(?:bearer|basic)\s+[A-Za-z0-9._~+/=-]+/gi, "[REDACTED_AUTH]")
|
|
64
|
-
.replace(/\b(?:token|secret|password|passwd|api[_-]?key|authorization|cookie)\s*[:=]\s*[^\s,;]+/gi, "$1=[REDACTED]");
|
|
65
|
-
if (redacted.length > maxLength) redacted = `${redacted.slice(0, maxLength - 1)}…`;
|
|
66
|
-
return redacted;
|
|
67
|
-
}
|
|
68
|
-
|
|
69
|
-
function messageKind(message: JSONRPCMessage): McpTraceMessageKind {
|
|
70
|
-
if ("method" in message) return "id" in message ? "request" : "notification";
|
|
71
|
-
return "response";
|
|
72
|
-
}
|
|
73
|
-
|
|
74
|
-
function traceId(value: unknown): string | number | null | undefined {
|
|
75
|
-
if (value === null) return null;
|
|
76
|
-
if (typeof value === "number" && Number.isFinite(value)) return value;
|
|
77
|
-
if (typeof value === "string") return "[REDACTED_ID]";
|
|
78
|
-
return undefined;
|
|
79
|
-
}
|
|
80
|
-
|
|
81
|
-
function messageBytes(message: JSONRPCMessage): number | undefined {
|
|
82
|
-
try {
|
|
83
|
-
return Buffer.byteLength(JSON.stringify(message), "utf8");
|
|
84
|
-
} catch {
|
|
85
|
-
return undefined;
|
|
86
|
-
}
|
|
87
|
-
}
|
|
88
|
-
|
|
89
|
-
export function createMcpTraceEvent(
|
|
90
|
-
direction: McpTraceDirection,
|
|
91
|
-
server: string,
|
|
92
|
-
transport: McpTraceTransport,
|
|
93
|
-
message: JSONRPCMessage,
|
|
94
|
-
status: "sent" | "received" | "error",
|
|
95
|
-
options?: { relatedRequestId?: unknown; durationMs?: number },
|
|
96
|
-
): McpTraceEvent {
|
|
97
|
-
const kind = messageKind(message);
|
|
98
|
-
const bytes = messageBytes(message);
|
|
99
|
-
const event: McpTraceEvent = {
|
|
100
|
-
version: MCP_TRACE_SCHEMA_VERSION,
|
|
101
|
-
timestamp: new Date().toISOString(),
|
|
102
|
-
direction,
|
|
103
|
-
server: redactTraceText(server, 120),
|
|
104
|
-
transport,
|
|
105
|
-
kind,
|
|
106
|
-
status,
|
|
107
|
-
...(bytes !== undefined ? { bytes } : {}),
|
|
108
|
-
};
|
|
109
|
-
if ("method" in message) event.method = redactTraceText(message.method, 120);
|
|
110
|
-
if ("id" in message) event.id = traceId(message.id) ?? null;
|
|
111
|
-
const relatedRequestId = traceId(options?.relatedRequestId);
|
|
112
|
-
if (relatedRequestId !== undefined && relatedRequestId !== null) event.relatedRequestId = relatedRequestId;
|
|
113
|
-
if ("error" in message && message.error && typeof message.error.code === "number") {
|
|
114
|
-
event.errorCode = message.error.code;
|
|
115
|
-
}
|
|
116
|
-
if (options?.durationMs !== undefined && Number.isFinite(options.durationMs)) {
|
|
117
|
-
event.durationMs = Math.max(0, Math.round(options.durationMs * 100) / 100);
|
|
118
|
-
}
|
|
119
|
-
return event;
|
|
120
|
-
}
|
|
121
|
-
|
|
122
|
-
export class McpTraceWriter {
|
|
123
|
-
private readonly maxBytes: number;
|
|
124
|
-
private readonly maxEvents: number;
|
|
125
|
-
private readonly append: NonNullable<McpTraceWriterOptions["appendFile"]>;
|
|
126
|
-
private readonly resetFile: NonNullable<McpTraceWriterOptions["writeFile"]>;
|
|
127
|
-
private readonly makeDirectory: NonNullable<McpTraceWriterOptions["mkdir"]>;
|
|
128
|
-
private bytesWritten = 0;
|
|
129
|
-
private eventsWritten = 0;
|
|
130
|
-
private queue = Promise.resolve();
|
|
131
|
-
private disabled = false;
|
|
132
|
-
private initializationFailed = false;
|
|
133
|
-
private persistenceError: unknown;
|
|
134
|
-
private readonly fileReady: Promise<void>;
|
|
135
|
-
|
|
136
|
-
constructor(private readonly options: McpTraceWriterOptions) {
|
|
137
|
-
this.maxBytes = boundedPositiveInteger(options.maxBytes, DEFAULT_MCP_TRACE_MAX_BYTES);
|
|
138
|
-
this.maxEvents = boundedPositiveInteger(options.maxEvents, DEFAULT_MCP_TRACE_MAX_EVENTS);
|
|
139
|
-
this.append = options.appendFile ?? (async (path, data, appendOptions) => {
|
|
140
|
-
await appendFile(path, data, appendOptions);
|
|
141
|
-
});
|
|
142
|
-
this.resetFile = options.writeFile ?? (async (path, data, writeOptions) => {
|
|
143
|
-
await writeFile(path, data, writeOptions);
|
|
144
|
-
});
|
|
145
|
-
this.makeDirectory = options.mkdir ?? (async path => {
|
|
146
|
-
await mkdir(path, { recursive: true });
|
|
147
|
-
return undefined;
|
|
148
|
-
});
|
|
149
|
-
this.fileReady = this.makeDirectory(dirname(this.options.filePath), { recursive: true })
|
|
150
|
-
.then(() => this.resetFile(this.options.filePath, "", { encoding: "utf8" }))
|
|
151
|
-
.catch(error => {
|
|
152
|
-
// Tracing must never change MCP request/response behavior.
|
|
153
|
-
this.persistenceError = error;
|
|
154
|
-
this.initializationFailed = true;
|
|
155
|
-
this.disabled = true;
|
|
156
|
-
});
|
|
157
|
-
}
|
|
158
|
-
|
|
159
|
-
get filePath(): string {
|
|
160
|
-
return this.options.filePath;
|
|
161
|
-
}
|
|
162
|
-
|
|
163
|
-
get isDisabled(): boolean {
|
|
164
|
-
return this.disabled;
|
|
165
|
-
}
|
|
166
|
-
|
|
167
|
-
get stats(): { bytes: number; events: number } {
|
|
168
|
-
return { bytes: this.bytesWritten, events: this.eventsWritten };
|
|
169
|
-
}
|
|
170
|
-
|
|
171
|
-
write(event: McpTraceEvent): void {
|
|
172
|
-
if (this.disabled || this.eventsWritten >= this.maxEvents) return;
|
|
173
|
-
let line: string;
|
|
174
|
-
try {
|
|
175
|
-
line = `${JSON.stringify(event)}\n`;
|
|
176
|
-
} catch {
|
|
177
|
-
this.disabled = true;
|
|
178
|
-
return;
|
|
179
|
-
}
|
|
180
|
-
const bytes = Buffer.byteLength(line, "utf8");
|
|
181
|
-
if (bytes > this.maxBytes - this.bytesWritten) {
|
|
182
|
-
this.disabled = true;
|
|
183
|
-
return;
|
|
184
|
-
}
|
|
185
|
-
|
|
186
|
-
this.bytesWritten += bytes;
|
|
187
|
-
this.eventsWritten += 1;
|
|
188
|
-
this.queue = this.queue.then(async () => {
|
|
189
|
-
await this.fileReady;
|
|
190
|
-
if (this.initializationFailed) return;
|
|
191
|
-
await this.append(this.options.filePath, line, { encoding: "utf8" });
|
|
192
|
-
}).catch(error => {
|
|
193
|
-
// Tracing must never change MCP request/response behavior.
|
|
194
|
-
this.persistenceError ??= error;
|
|
195
|
-
this.disabled = true;
|
|
196
|
-
});
|
|
197
|
-
}
|
|
198
|
-
|
|
199
|
-
async flush(strict = false): Promise<void> {
|
|
200
|
-
await this.fileReady;
|
|
201
|
-
await this.queue;
|
|
202
|
-
if (strict && this.persistenceError !== undefined) throw this.persistenceError;
|
|
203
|
-
}
|
|
204
|
-
}
|
|
205
|
-
|
|
206
|
-
export function createMcpTraceWriter(
|
|
207
|
-
sessionCwd: string | undefined,
|
|
208
|
-
settings: McpTraceSettings = {},
|
|
209
|
-
randomSuffix = Math.random().toString(36).slice(2, 10),
|
|
210
|
-
): McpTraceWriter {
|
|
211
|
-
const timestamp = new Date().toISOString().replace(/[:.]/g, "-");
|
|
212
|
-
const configuredPath = settings.file;
|
|
213
|
-
const filePath = configuredPath
|
|
214
|
-
? (isAbsolute(configuredPath) ? configuredPath : resolve(sessionCwd ?? process.cwd(), configuredPath))
|
|
215
|
-
: resolve(sessionCwd ?? process.cwd(), ".pi", "fitch-mcp-adapter", "traces", `mcp-${timestamp}-${randomSuffix}.jsonl`);
|
|
216
|
-
return new McpTraceWriter({
|
|
217
|
-
filePath,
|
|
218
|
-
...(settings.maxBytes !== undefined ? { maxBytes: settings.maxBytes } : {}),
|
|
219
|
-
...(settings.maxEvents !== undefined ? { maxEvents: settings.maxEvents } : {}),
|
|
220
|
-
});
|
|
221
|
-
}
|
|
222
|
-
|
|
223
|
-
export interface McpTraceObserver {
|
|
224
|
-
record(event: McpTraceEvent): void;
|
|
225
|
-
}
|
|
226
|
-
|
|
227
|
-
export function isMcpTraceEnabled(
|
|
228
|
-
definition: { trace?: boolean },
|
|
229
|
-
settings?: McpTraceSettings,
|
|
230
|
-
): boolean {
|
|
231
|
-
return definition.trace ?? settings?.enabled === true;
|
|
232
|
-
}
|
|
233
|
-
|
|
234
|
-
/**
|
|
235
|
-
* Compose the SDK's transport callbacks instead of replacing them. Protocol
|
|
236
|
-
* assigns `onmessage` during connect, so the setter must keep the observer in
|
|
237
|
-
* front of whichever callback the SDK installs.
|
|
238
|
-
*/
|
|
239
|
-
export function wrapTransportWithMcpTrace(
|
|
240
|
-
transport: Transport,
|
|
241
|
-
server: string,
|
|
242
|
-
transportKind: McpTraceTransport,
|
|
243
|
-
observer: McpTraceObserver,
|
|
244
|
-
): Transport {
|
|
245
|
-
let messageHandler = transport.onmessage;
|
|
246
|
-
const record = (event: McpTraceEvent): void => {
|
|
247
|
-
try {
|
|
248
|
-
observer.record(event);
|
|
249
|
-
} catch {
|
|
250
|
-
// An observer failure must never alter SDK transport behavior.
|
|
251
|
-
}
|
|
252
|
-
};
|
|
253
|
-
// Instrument the native instance: the SDK inspects stdio identity and HTTP
|
|
254
|
-
// hasPerRequestStream to choose negotiation and cancellation behavior.
|
|
255
|
-
const send = transport.send.bind(transport);
|
|
256
|
-
transport.send = async (message, options) => {
|
|
257
|
-
const started = performance.now();
|
|
258
|
-
const messages = Array.isArray(message) ? message : [message];
|
|
259
|
-
try {
|
|
260
|
-
await send(message, options);
|
|
261
|
-
for (const item of messages) {
|
|
262
|
-
record(createMcpTraceEvent("outbound", server, transportKind, item, "sent", {
|
|
263
|
-
durationMs: performance.now() - started,
|
|
264
|
-
}));
|
|
265
|
-
}
|
|
266
|
-
} catch (error) {
|
|
267
|
-
for (const item of messages) {
|
|
268
|
-
record(createMcpTraceEvent("outbound", server, transportKind, item, "error", {
|
|
269
|
-
durationMs: performance.now() - started,
|
|
270
|
-
}));
|
|
271
|
-
}
|
|
272
|
-
throw error;
|
|
273
|
-
}
|
|
274
|
-
};
|
|
275
|
-
Object.defineProperty(transport, "onmessage", {
|
|
276
|
-
configurable: true,
|
|
277
|
-
get: () => messageHandler,
|
|
278
|
-
set: (handler: Transport["onmessage"]) => {
|
|
279
|
-
messageHandler = handler ? (message: JSONRPCMessage, extra?: MessageExtraInfo) => {
|
|
280
|
-
record(createMcpTraceEvent("inbound", server, transportKind, message, "received"));
|
|
281
|
-
handler(message, extra);
|
|
282
|
-
} : undefined;
|
|
283
|
-
},
|
|
284
|
-
});
|
|
285
|
-
return transport;
|
|
286
|
-
}
|
|
287
|
-
|
|
288
|
-
export function traceTransportKind(definition: { command?: string; url?: string; socket?: string }, transport: Transport): McpTraceTransport {
|
|
289
|
-
if (definition.command) return "stdio";
|
|
290
|
-
if (definition.socket) return "unix-socket";
|
|
291
|
-
const constructorName = transport.constructor?.name.toLowerCase() ?? "";
|
|
292
|
-
if (constructorName.includes("sse")) return "sse";
|
|
293
|
-
if (constructorName.includes("streamable")) return "streamable-http";
|
|
294
|
-
return definition.url ? "streamable-http" : "unknown";
|
|
295
|
-
}
|
package/metadata-cache.ts
DELETED
|
@@ -1,271 +0,0 @@
|
|
|
1
|
-
// metadata-cache.ts - Persistent MCP metadata cache
|
|
2
|
-
import { existsSync, readFileSync, writeFileSync, renameSync, mkdirSync } from "node:fs";
|
|
3
|
-
import { dirname } from "node:path";
|
|
4
|
-
import { getAdapterPath } from "./agent-dir.ts";
|
|
5
|
-
import { createHash } from "node:crypto";
|
|
6
|
-
import type {
|
|
7
|
-
CachedPrompt,
|
|
8
|
-
CachedResource,
|
|
9
|
-
CachedTool,
|
|
10
|
-
McpConfig,
|
|
11
|
-
McpTool,
|
|
12
|
-
McpResource,
|
|
13
|
-
McpPrompt,
|
|
14
|
-
McpPromptArgument,
|
|
15
|
-
MetadataCache,
|
|
16
|
-
ServerCacheEntry,
|
|
17
|
-
ServerEntry,
|
|
18
|
-
ToolMetadata,
|
|
19
|
-
PromptMetadata,
|
|
20
|
-
} from "./types.ts";
|
|
21
|
-
import { formatPromptCommandName, isServerDisabled, resolveToolPrefix, type ToolPrefix } from "./types.ts";
|
|
22
|
-
import { buildToolMetadata } from "./tool-metadata.ts";
|
|
23
|
-
import {
|
|
24
|
-
interpolateEnvRecord,
|
|
25
|
-
resolveBearerToken,
|
|
26
|
-
resolveConfigPath,
|
|
27
|
-
resolveServerUrl,
|
|
28
|
-
} from "./utils.ts";
|
|
29
|
-
|
|
30
|
-
// Version 2 stores raw descriptors; version 1 readers cannot enforce raw UI visibility.
|
|
31
|
-
const CACHE_VERSION = 2;
|
|
32
|
-
const CACHE_MAX_AGE_MS = 7 * 24 * 60 * 60 * 1000;
|
|
33
|
-
|
|
34
|
-
export type { CachedPrompt, CachedResource, CachedTool, MetadataCache, ServerCacheEntry } from "./types.ts";
|
|
35
|
-
|
|
36
|
-
export function getMetadataCachePath(): string {
|
|
37
|
-
return getAdapterPath("mcp-cache.json");
|
|
38
|
-
}
|
|
39
|
-
|
|
40
|
-
export function loadMetadataCache(enabled = true): MetadataCache | null {
|
|
41
|
-
if (!enabled) return null;
|
|
42
|
-
const cachePath = getMetadataCachePath();
|
|
43
|
-
if (!existsSync(cachePath)) return null;
|
|
44
|
-
try {
|
|
45
|
-
const raw = JSON.parse(readFileSync(cachePath, "utf-8"));
|
|
46
|
-
if (!raw || typeof raw !== "object") return null;
|
|
47
|
-
if (raw.version !== 1 && raw.version !== CACHE_VERSION) return null;
|
|
48
|
-
if (!raw.servers || typeof raw.servers !== "object") return null;
|
|
49
|
-
return raw as MetadataCache;
|
|
50
|
-
} catch {
|
|
51
|
-
return null;
|
|
52
|
-
}
|
|
53
|
-
}
|
|
54
|
-
|
|
55
|
-
export function saveMetadataCache(cache: MetadataCache, enabled = true): void {
|
|
56
|
-
if (!enabled) return;
|
|
57
|
-
const cachePath = getMetadataCachePath();
|
|
58
|
-
const dir = dirname(cachePath);
|
|
59
|
-
mkdirSync(dir, { recursive: true });
|
|
60
|
-
|
|
61
|
-
let merged: MetadataCache = { version: CACHE_VERSION, servers: {} };
|
|
62
|
-
try {
|
|
63
|
-
if (existsSync(cachePath)) {
|
|
64
|
-
const existing = JSON.parse(readFileSync(cachePath, "utf-8")) as MetadataCache;
|
|
65
|
-
if (existing && (existing.version === 1 || existing.version === CACHE_VERSION) && existing.servers) {
|
|
66
|
-
merged.servers = { ...existing.servers };
|
|
67
|
-
}
|
|
68
|
-
}
|
|
69
|
-
} catch {
|
|
70
|
-
// Ignore parse errors and proceed with empty cache
|
|
71
|
-
}
|
|
72
|
-
|
|
73
|
-
merged.version = CACHE_VERSION;
|
|
74
|
-
merged.servers = { ...merged.servers, ...cache.servers };
|
|
75
|
-
|
|
76
|
-
const tmpPath = `${cachePath}.${process.pid}.tmp`;
|
|
77
|
-
writeFileSync(tmpPath, JSON.stringify(merged, null, 2), "utf-8");
|
|
78
|
-
renameSync(tmpPath, cachePath);
|
|
79
|
-
}
|
|
80
|
-
|
|
81
|
-
export function computeServerHash(definition: ServerEntry): string {
|
|
82
|
-
// Hash only fields that affect server identity and tool/resource output.
|
|
83
|
-
// Exclude lifecycle, idleTimeout, requestTimeoutMs, debug — those are runtime behavior settings
|
|
84
|
-
// that don't change which tools a server exposes.
|
|
85
|
-
const identity: Record<string, unknown> = {
|
|
86
|
-
command: definition.command,
|
|
87
|
-
args: definition.args,
|
|
88
|
-
socket: resolveConfigPath(definition.socket),
|
|
89
|
-
env: interpolateEnvRecord(definition.env),
|
|
90
|
-
cwd: resolveConfigPath(definition.cwd),
|
|
91
|
-
url: resolveServerUrl(definition),
|
|
92
|
-
headers: interpolateEnvRecord(definition.headers),
|
|
93
|
-
auth: definition.auth,
|
|
94
|
-
bearerToken: resolveBearerToken(definition),
|
|
95
|
-
bearerTokenEnv: definition.bearerTokenEnv,
|
|
96
|
-
exposeResources: definition.exposeResources,
|
|
97
|
-
includeTools: definition.includeTools,
|
|
98
|
-
excludeTools: definition.excludeTools,
|
|
99
|
-
};
|
|
100
|
-
const normalized = stableStringify(identity);
|
|
101
|
-
return createHash("sha256").update(normalized).digest("hex");
|
|
102
|
-
}
|
|
103
|
-
|
|
104
|
-
export function isServerCacheValid(
|
|
105
|
-
entry: ServerCacheEntry,
|
|
106
|
-
definition: ServerEntry,
|
|
107
|
-
maxAgeMs: number = CACHE_MAX_AGE_MS
|
|
108
|
-
): boolean {
|
|
109
|
-
let configHash: string;
|
|
110
|
-
try {
|
|
111
|
-
configHash = computeServerHash(definition);
|
|
112
|
-
} catch {
|
|
113
|
-
return false;
|
|
114
|
-
}
|
|
115
|
-
if (!entry || entry.configHash !== configHash) return false;
|
|
116
|
-
if (!entry.cachedAt || typeof entry.cachedAt !== "number") return false;
|
|
117
|
-
if (maxAgeMs > 0 && Date.now() - entry.cachedAt > maxAgeMs) return false;
|
|
118
|
-
return true;
|
|
119
|
-
}
|
|
120
|
-
|
|
121
|
-
export function parseDirectToolSelectors(selectors: string[]): {
|
|
122
|
-
servers: Set<string>;
|
|
123
|
-
tools: Map<string, Set<string>>;
|
|
124
|
-
} {
|
|
125
|
-
const servers = new Set<string>();
|
|
126
|
-
const tools = new Map<string, Set<string>>();
|
|
127
|
-
|
|
128
|
-
for (let selector of selectors) {
|
|
129
|
-
selector = selector.replace(/\/+$/, "");
|
|
130
|
-
if (selector.includes("/")) {
|
|
131
|
-
const [server, tool] = selector.split("/", 2);
|
|
132
|
-
if (server && tool) {
|
|
133
|
-
const serverTools = tools.get(server) ?? new Set<string>();
|
|
134
|
-
serverTools.add(tool);
|
|
135
|
-
tools.set(server, serverTools);
|
|
136
|
-
} else if (server) {
|
|
137
|
-
servers.add(server);
|
|
138
|
-
}
|
|
139
|
-
} else if (selector) {
|
|
140
|
-
servers.add(selector);
|
|
141
|
-
}
|
|
142
|
-
}
|
|
143
|
-
|
|
144
|
-
return { servers, tools };
|
|
145
|
-
}
|
|
146
|
-
|
|
147
|
-
export function getMissingConfiguredDirectToolServers(
|
|
148
|
-
config: McpConfig,
|
|
149
|
-
cache: MetadataCache | null,
|
|
150
|
-
envOverride?: string[],
|
|
151
|
-
): string[] {
|
|
152
|
-
const missing: string[] = [];
|
|
153
|
-
const globalDirect = config.settings?.directTools;
|
|
154
|
-
const envSelection = envOverride ? parseDirectToolSelectors(envOverride) : null;
|
|
155
|
-
|
|
156
|
-
for (const [serverName, definition] of Object.entries(config.mcpServers)) {
|
|
157
|
-
if (isServerDisabled(definition)) continue;
|
|
158
|
-
const hasDirectTools = envSelection
|
|
159
|
-
? envSelection.servers.has(serverName) || envSelection.tools.has(serverName)
|
|
160
|
-
: definition.directTools !== undefined
|
|
161
|
-
? !!definition.directTools
|
|
162
|
-
: !!globalDirect;
|
|
163
|
-
|
|
164
|
-
if (!hasDirectTools) continue;
|
|
165
|
-
|
|
166
|
-
const serverCache = cache?.servers?.[serverName];
|
|
167
|
-
if (!serverCache || !isServerCacheValid(serverCache, definition)) {
|
|
168
|
-
missing.push(serverName);
|
|
169
|
-
}
|
|
170
|
-
}
|
|
171
|
-
|
|
172
|
-
return missing;
|
|
173
|
-
}
|
|
174
|
-
|
|
175
|
-
export function reconstructToolMetadata(
|
|
176
|
-
serverName: string,
|
|
177
|
-
entry: ServerCacheEntry,
|
|
178
|
-
prefix: ToolPrefix,
|
|
179
|
-
definition: Pick<ServerEntry, "exposeResources" | "includeTools" | "excludeTools" | "toolPrefix" | "disabled">
|
|
180
|
-
): ToolMetadata[] {
|
|
181
|
-
return buildToolMetadata(
|
|
182
|
-
(entry.tools ?? []).filter(tool => tool?.name).map(restoreCachedTool),
|
|
183
|
-
entry.resources ?? [],
|
|
184
|
-
definition,
|
|
185
|
-
serverName,
|
|
186
|
-
prefix,
|
|
187
|
-
).metadata;
|
|
188
|
-
}
|
|
189
|
-
|
|
190
|
-
function restoreCachedTool(tool: CachedTool): McpTool {
|
|
191
|
-
const { uiResourceUri, uiVisibility, uiStreamMode, ...descriptor } = tool;
|
|
192
|
-
if (descriptor._meta !== undefined || (uiResourceUri === undefined && uiVisibility === undefined && uiStreamMode === undefined)) {
|
|
193
|
-
return descriptor;
|
|
194
|
-
}
|
|
195
|
-
return {
|
|
196
|
-
...descriptor,
|
|
197
|
-
_meta: {
|
|
198
|
-
ui: {
|
|
199
|
-
...(uiResourceUri !== undefined ? { resourceUri: uiResourceUri } : {}),
|
|
200
|
-
...(uiVisibility !== undefined ? { visibility: uiVisibility } : {}),
|
|
201
|
-
...(uiStreamMode !== undefined ? { "pi-mcp-adapter.streamMode": uiStreamMode } : {}),
|
|
202
|
-
},
|
|
203
|
-
},
|
|
204
|
-
};
|
|
205
|
-
}
|
|
206
|
-
|
|
207
|
-
export function serializeTools(tools: McpTool[]): CachedTool[] {
|
|
208
|
-
return tools.filter(tool => tool?.name);
|
|
209
|
-
}
|
|
210
|
-
|
|
211
|
-
export function serializeResources(resources: McpResource[]): CachedResource[] {
|
|
212
|
-
return resources.filter(resource => resource?.name && resource?.uri);
|
|
213
|
-
}
|
|
214
|
-
|
|
215
|
-
export function serializePrompts(prompts: McpPrompt[]): CachedPrompt[] {
|
|
216
|
-
return (prompts ?? [])
|
|
217
|
-
.filter(prompt => prompt?.name)
|
|
218
|
-
.map(prompt => ({
|
|
219
|
-
name: prompt.name,
|
|
220
|
-
...(prompt.title !== undefined ? { title: prompt.title } : {}),
|
|
221
|
-
...(prompt.description !== undefined ? { description: prompt.description } : {}),
|
|
222
|
-
...(Array.isArray(prompt.arguments)
|
|
223
|
-
? {
|
|
224
|
-
arguments: prompt.arguments.filter(argument => argument?.name).map(argument => ({
|
|
225
|
-
name: argument.name,
|
|
226
|
-
...(argument.description !== undefined ? { description: argument.description } : {}),
|
|
227
|
-
...(argument.required !== undefined ? { required: argument.required } : {}),
|
|
228
|
-
})),
|
|
229
|
-
}
|
|
230
|
-
: {}),
|
|
231
|
-
}));
|
|
232
|
-
}
|
|
233
|
-
|
|
234
|
-
export function reconstructPromptMetadata(
|
|
235
|
-
serverName: string,
|
|
236
|
-
prompts: ReadonlyArray<McpPrompt | CachedPrompt>,
|
|
237
|
-
prefix: ToolPrefix,
|
|
238
|
-
definition?: Pick<ServerEntry, "toolPrefix">,
|
|
239
|
-
): PromptMetadata[] {
|
|
240
|
-
const effectivePrefix = resolveToolPrefix(definition, prefix);
|
|
241
|
-
return (prompts ?? []).filter(prompt => prompt?.name).map(prompt => {
|
|
242
|
-
const args: McpPromptArgument[] = Array.isArray(prompt.arguments)
|
|
243
|
-
? prompt.arguments.filter(argument => argument?.name).map(argument => ({
|
|
244
|
-
name: argument.name,
|
|
245
|
-
...(argument.description !== undefined ? { description: argument.description } : {}),
|
|
246
|
-
...(argument.required !== undefined ? { required: argument.required } : {}),
|
|
247
|
-
}))
|
|
248
|
-
: [];
|
|
249
|
-
return {
|
|
250
|
-
serverName,
|
|
251
|
-
originalName: prompt.name,
|
|
252
|
-
commandName: formatPromptCommandName(prompt.name, serverName, effectivePrefix),
|
|
253
|
-
...(prompt.title !== undefined ? { title: prompt.title } : {}),
|
|
254
|
-
description: prompt.description ?? "",
|
|
255
|
-
arguments: args,
|
|
256
|
-
};
|
|
257
|
-
});
|
|
258
|
-
}
|
|
259
|
-
|
|
260
|
-
function stableStringify(value: unknown): string {
|
|
261
|
-
if (value === null || value === undefined || typeof value !== "object") {
|
|
262
|
-
const serialized = JSON.stringify(value);
|
|
263
|
-
return serialized === undefined ? "undefined" : serialized;
|
|
264
|
-
}
|
|
265
|
-
if (Array.isArray(value)) {
|
|
266
|
-
return `[${value.map(v => stableStringify(v)).join(",")}]`;
|
|
267
|
-
}
|
|
268
|
-
const obj = value as Record<string, unknown>;
|
|
269
|
-
const keys = Object.keys(obj).sort();
|
|
270
|
-
return `{${keys.map(k => `${JSON.stringify(k)}:${stableStringify(obj[k])}`).join(",")}}`;
|
|
271
|
-
}
|