@njuptlzf/mcp-adapter 2.29.0-0.0.1
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 +1205 -0
- package/LICENSE +21 -0
- package/MAPPING.md +73 -0
- package/README.md +564 -0
- package/abort.ts +34 -0
- package/adapters/pi-renderer.ts +7 -0
- package/adapters/protocol-elicitation-forwarder.ts +164 -0
- package/adapters/protocol-sampling-forwarder.ts +108 -0
- package/adapters/universal-host.ts +213 -0
- package/agent-dir.ts +68 -0
- package/agent-plugin-loader.ts +377 -0
- package/app-bridge.bundle.js +67 -0
- package/banner.png +0 -0
- package/bin/mcp-server.ts +282 -0
- package/cli.js +392 -0
- package/commands.ts +735 -0
- package/config.ts +1284 -0
- package/consent-manager.ts +64 -0
- package/direct-tools.ts +619 -0
- package/dist/agent-dir.d.ts +10 -0
- package/dist/agent-dir.js +63 -0
- package/dist/agent-dir.js.map +1 -0
- package/dist/agent-plugin-loader.d.ts +8 -0
- package/dist/agent-plugin-loader.js +356 -0
- package/dist/agent-plugin-loader.js.map +1 -0
- package/dist/config.d.ts +123 -0
- package/dist/config.js +1087 -0
- package/dist/config.js.map +1 -0
- package/dist/metadata-cache.d.ts +19 -0
- package/dist/metadata-cache.js +319 -0
- package/dist/metadata-cache.js.map +1 -0
- package/dist/package-mcp-loader.d.ts +2 -0
- package/dist/package-mcp-loader.js +156 -0
- package/dist/package-mcp-loader.js.map +1 -0
- package/dist/resource-tools.d.ts +1 -0
- package/dist/resource-tools.js +15 -0
- package/dist/resource-tools.js.map +1 -0
- package/dist/types.d.ts +564 -0
- package/dist/types.js +287 -0
- package/dist/types.js.map +1 -0
- package/dist/ui-app-bridge-helpers.d.ts +6 -0
- package/dist/ui-app-bridge-helpers.js +37 -0
- package/dist/ui-app-bridge-helpers.js.map +1 -0
- package/dist/ui-stream-types.d.ts +104 -0
- package/dist/ui-stream-types.js +59 -0
- package/dist/ui-stream-types.js.map +1 -0
- package/dist/ui-tool-visibility.d.ts +4 -0
- package/dist/ui-tool-visibility.js +27 -0
- package/dist/ui-tool-visibility.js.map +1 -0
- package/dist/utils.d.ts +32 -0
- package/dist/utils.js +338 -0
- package/dist/utils.js.map +1 -0
- package/elicitation-handler.ts +348 -0
- package/error-signal.ts +21 -0
- package/errors.ts +223 -0
- package/failure-backoff.ts +23 -0
- package/glimpse-ui.ts +80 -0
- package/host-html-template.ts +461 -0
- package/index.ts +1291 -0
- package/init.ts +692 -0
- package/interfaces/agent-paths.ts +67 -0
- package/interfaces/host-types.ts +102 -0
- package/interfaces/sampling.ts +57 -0
- package/json-schema-validator.ts +69 -0
- package/lifecycle.ts +446 -0
- package/logger.ts +169 -0
- package/mcp-auth-flow.ts +1026 -0
- package/mcp-auth.ts +1000 -0
- package/mcp-bearer-store.ts +387 -0
- package/mcp-callback-server.ts +534 -0
- package/mcp-code.ts +360 -0
- package/mcp-keyring-helper.cjs +89 -0
- package/mcp-oauth-provider.ts +666 -0
- package/mcp-output-guard.ts +496 -0
- package/mcp-panel.ts +1044 -0
- package/mcp-probe.ts +201 -0
- package/mcp-references.ts +368 -0
- package/mcp-script-worker.mjs +130 -0
- package/mcp-server.mjs +2133 -0
- package/mcp-setup-panel.ts +667 -0
- package/mcp-status.ts +98 -0
- package/mcp-trace.ts +306 -0
- package/metadata-cache.ts +382 -0
- package/namespace-tools.ts +276 -0
- package/npx-resolver.ts +543 -0
- package/oauth-handler.ts +30 -0
- package/oauth.ts +48 -0
- package/onboarding-state.ts +76 -0
- package/package-mcp-loader.ts +168 -0
- package/package.json +225 -0
- package/panel-keys.ts +53 -0
- package/prompts.ts +353 -0
- package/proxy-modes.ts +1418 -0
- package/request-headers-command.ts +330 -0
- package/resource-tools.ts +17 -0
- package/runtime-owner.ts +91 -0
- package/sampling-handler.ts +284 -0
- package/search-ranking.ts +278 -0
- package/server-manager.ts +1318 -0
- package/session-recovery.ts +158 -0
- package/skills/README.md +64 -0
- package/skills/mcp-adapter/SKILL.md +332 -0
- package/skills/mcp-adapter/references/deploy-examples.md +259 -0
- package/skills/mcp-adapter/references/deploy.md +89 -0
- package/skills/mcp-adapter/references/generate.md +144 -0
- package/skills/mcp-adapter/references/resolver.md +105 -0
- package/skills/mcp-adapter/references/verify.md +157 -0
- package/skills/mcp-scripting/SKILL.md +38 -0
- package/skills/resolve-conflicts/SKILL.md +482 -0
- package/skills/resolve-conflicts/references/patterns.md +432 -0
- package/skills/resolve-conflicts/references/sample-plan.md +96 -0
- package/skills/resolve-conflicts/scripts/handle-deleted-modified.sh +183 -0
- package/skills/resolve-conflicts/scripts/validate-conflicts.sh +120 -0
- package/skills/upstream-merge/SKILL.md +486 -0
- package/skills/upstream-merge/references/pi-coupling-markers.md +129 -0
- package/skills/upstream-merge/references/special-cases.md +39 -0
- package/state.ts +60 -0
- package/tool-approval.ts +195 -0
- package/tool-metadata.ts +296 -0
- package/tool-registrar.ts +253 -0
- package/tool-result-renderer.ts +477 -0
- package/ts-shape.ts +149 -0
- package/types.ts +991 -0
- package/ui-app-bridge-helpers.ts +40 -0
- package/ui-resource-handler.ts +250 -0
- package/ui-server.ts +852 -0
- package/ui-session.ts +571 -0
- package/ui-stream-types.ts +89 -0
- package/ui-tool-visibility.ts +25 -0
- package/unix-socket-transport.ts +85 -0
- package/utils.ts +382 -0
package/banner.png
ADDED
|
Binary file
|
|
@@ -0,0 +1,282 @@
|
|
|
1
|
+
#!/usr/bin/env npx tsx
|
|
2
|
+
/**
|
|
3
|
+
* bin/mcp-server.ts — Universal MCP stdio server entry point.
|
|
4
|
+
*
|
|
5
|
+
* Stage 2 (fork-host, not fork-engine): this entry point now installs the
|
|
6
|
+
* UPSTREAM engine (`index.ts`'s `createMcpAdapter`) onto a `UniversalMcpHost`
|
|
7
|
+
* that presents the Pi `ExtensionAPI` surface. The fork's parallel engine
|
|
8
|
+
* (`adapters/entry.ts`) is no longer used here.
|
|
9
|
+
*
|
|
10
|
+
* D-04/D-05: the host is agent-agnostic; no per-agent adapter import.
|
|
11
|
+
* D-06/D-07: protocol forwarders are injected when the Agent Client declares
|
|
12
|
+
* sampling/elicitation capabilities.
|
|
13
|
+
* D-11: pure forwarding — no config.settings checks. Client capability
|
|
14
|
+
* declaration is the only gate.
|
|
15
|
+
*
|
|
16
|
+
* Pitfall 1 (flow reordering): MCP Server is created and connected BEFORE
|
|
17
|
+
* fireSessionStart(), enabling runtime capability discovery and forwarder
|
|
18
|
+
* injection before initializeMcp() runs.
|
|
19
|
+
* Pitfall 5: Uses server.getClientCapabilities() NOT the server's own
|
|
20
|
+
* capabilities method.
|
|
21
|
+
* Pitfall 4: Sets ctx.hasUI = true when forwarders are injected, satisfying
|
|
22
|
+
* init.ts conditions without modifying init.ts.
|
|
23
|
+
*
|
|
24
|
+
* Usage:
|
|
25
|
+
* mcp-server # auto-discover .mcp.json
|
|
26
|
+
* mcp-server --config /path/to/mcp.json # explicit config path
|
|
27
|
+
* mcp-server --help # show usage
|
|
28
|
+
*
|
|
29
|
+
* Registration in agent config:
|
|
30
|
+
* {
|
|
31
|
+
* "mcpServers": {
|
|
32
|
+
* "mcp-adapter": {
|
|
33
|
+
* "command": "mcp-server"
|
|
34
|
+
* }
|
|
35
|
+
* }
|
|
36
|
+
* }
|
|
37
|
+
*
|
|
38
|
+
* This file is fork-only (upstream has no bin/ directory).
|
|
39
|
+
*/
|
|
40
|
+
|
|
41
|
+
import { createMcpAdapter } from "../index.ts";
|
|
42
|
+
import { UniversalMcpHost } from "../adapters/universal-host.ts";
|
|
43
|
+
import { ProtocolSamplingForwarder } from "../adapters/protocol-sampling-forwarder.ts";
|
|
44
|
+
import { ProtocolElicitationForwarder } from "../adapters/protocol-elicitation-forwarder.ts";
|
|
45
|
+
import { loadMcpConfig } from "../config.ts";
|
|
46
|
+
import { createUniversalResolver } from "../interfaces/agent-paths.ts";
|
|
47
|
+
import type { AgentChannel, FormConfig, UISystem } from "../interfaces/host-types.ts";
|
|
48
|
+
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
|
|
49
|
+
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
|
|
50
|
+
import {
|
|
51
|
+
CallToolRequestSchema,
|
|
52
|
+
ListToolsRequestSchema,
|
|
53
|
+
} from "@modelcontextprotocol/sdk/types.js";
|
|
54
|
+
|
|
55
|
+
const SERVER_NAME = "mcp-adapter";
|
|
56
|
+
const SERVER_VERSION = "2.29.0-0.0.1";
|
|
57
|
+
const GENERIC_GLOBAL_CONFIG_PATH = createUniversalResolver().globalConfigPath();
|
|
58
|
+
|
|
59
|
+
// ---------------------------------------------------------------------------
|
|
60
|
+
// CLI argument parsing
|
|
61
|
+
// ---------------------------------------------------------------------------
|
|
62
|
+
|
|
63
|
+
function showHelp(): void {
|
|
64
|
+
console.log(`
|
|
65
|
+
Usage: mcp-server [options]
|
|
66
|
+
|
|
67
|
+
Universal MCP stdio server — bridges mcp-adapter proxy tool into any
|
|
68
|
+
MCP-compatible agent via stdio transport.
|
|
69
|
+
|
|
70
|
+
Options:
|
|
71
|
+
--config <path> Path to mcp.json config file
|
|
72
|
+
--help Show this help message
|
|
73
|
+
--version Show version
|
|
74
|
+
|
|
75
|
+
Environment:
|
|
76
|
+
MCP_CONFIG_PATH Alternative way to specify config path
|
|
77
|
+
|
|
78
|
+
Config discovery (in priority order):
|
|
79
|
+
1. --config flag
|
|
80
|
+
2. MCP_CONFIG_PATH env var
|
|
81
|
+
3. .mcp.json in current working directory
|
|
82
|
+
4. ~/.config/mcp/mcp.json (shared global)
|
|
83
|
+
`);
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
function parseArgs(argv: string[]): { configPath?: string; showHelp: boolean; showVersion: boolean } {
|
|
87
|
+
let configPath: string | undefined;
|
|
88
|
+
let showHelp = false;
|
|
89
|
+
let showVersion = false;
|
|
90
|
+
|
|
91
|
+
for (let i = 2; i < argv.length; i++) {
|
|
92
|
+
const arg = argv[i];
|
|
93
|
+
if (arg === "--help" || arg === "-h") {
|
|
94
|
+
showHelp = true;
|
|
95
|
+
} else if (arg === "--version" || arg === "-v") {
|
|
96
|
+
showVersion = true;
|
|
97
|
+
} else if (arg === "--config") {
|
|
98
|
+
configPath = argv[++i];
|
|
99
|
+
if (!configPath) {
|
|
100
|
+
console.error("Error: --config requires a path argument");
|
|
101
|
+
process.exit(1);
|
|
102
|
+
}
|
|
103
|
+
} else if (arg.startsWith("--config=")) {
|
|
104
|
+
configPath = arg.slice("--config=".length);
|
|
105
|
+
} else {
|
|
106
|
+
console.error(`Unknown option: ${arg}`);
|
|
107
|
+
console.error("Run 'mcp-server --help' for usage.");
|
|
108
|
+
process.exit(1);
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
// Fall back to env var if no --config flag (D-02: universal config path discovery)
|
|
113
|
+
if (!configPath && process.env.MCP_CONFIG_PATH) {
|
|
114
|
+
configPath = process.env.MCP_CONFIG_PATH;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
return { configPath, showHelp, showVersion };
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
// ---------------------------------------------------------------------------
|
|
121
|
+
// main() — reordered flow per Pitfall 1
|
|
122
|
+
// ---------------------------------------------------------------------------
|
|
123
|
+
|
|
124
|
+
async function main(): Promise<void> {
|
|
125
|
+
// Step 1: Parse args, handle help/version
|
|
126
|
+
const args = parseArgs(process.argv);
|
|
127
|
+
|
|
128
|
+
if (args.showHelp) {
|
|
129
|
+
showHelp();
|
|
130
|
+
return;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
if (args.showVersion) {
|
|
134
|
+
console.log(SERVER_VERSION);
|
|
135
|
+
return;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
// Step 2: Load config using universal resolver (D-02: no agent-specific paths).
|
|
139
|
+
// The upstream engine loads metadata cache itself; here we only pre-load
|
|
140
|
+
// config for the startup log and pass it programmatically.
|
|
141
|
+
const config = loadMcpConfig(args.configPath, process.cwd(), GENERIC_GLOBAL_CONFIG_PATH);
|
|
142
|
+
const serverCount = Object.keys(config.mcpServers || {}).length;
|
|
143
|
+
console.error(`[mcp-server] Config loaded: ${serverCount} server(s) configured`);
|
|
144
|
+
|
|
145
|
+
if (serverCount === 0) {
|
|
146
|
+
console.error("[mcp-server] Warning: no MCP servers configured. Create a .mcp.json file or use --config <path>.");
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
// Step 3: Install the UPSTREAM engine onto a UniversalMcpHost (Stage 2).
|
|
150
|
+
const host = new UniversalMcpHost();
|
|
151
|
+
const install = createMcpAdapter({ config });
|
|
152
|
+
install(host);
|
|
153
|
+
|
|
154
|
+
// Step 4: Attach AgentChannel — routes host sendMessage to stderr
|
|
155
|
+
// (MCP stdio uses stdout for protocol; stderr is for diagnostics)
|
|
156
|
+
const channel: AgentChannel = {
|
|
157
|
+
send: (msg: unknown) => {
|
|
158
|
+
const text = typeof msg === "string" ? msg : JSON.stringify(msg);
|
|
159
|
+
console.error(`[mcp-server] adapter message: ${text}`);
|
|
160
|
+
},
|
|
161
|
+
};
|
|
162
|
+
host.attachChannel(channel);
|
|
163
|
+
|
|
164
|
+
// Step 5: Create MCP Server
|
|
165
|
+
const server = new Server(
|
|
166
|
+
{ name: SERVER_NAME, version: SERVER_VERSION },
|
|
167
|
+
{ capabilities: { tools: {} } },
|
|
168
|
+
);
|
|
169
|
+
|
|
170
|
+
// Step 6: Set request handlers (ListTools filtered to the active tool surface)
|
|
171
|
+
server.setRequestHandler(ListToolsRequestSchema, async () => {
|
|
172
|
+
const active = host.getActiveTools();
|
|
173
|
+
const visibleNames = active.length > 0 ? active : [...host.tools.keys()];
|
|
174
|
+
const mcpTools = visibleNames
|
|
175
|
+
.map((name) => host.tools.get(name))
|
|
176
|
+
.filter((tool): tool is NonNullable<typeof tool> => Boolean(tool))
|
|
177
|
+
.map((tool) => ({
|
|
178
|
+
name: tool.name,
|
|
179
|
+
description: tool.description || `MCP proxy tool: ${tool.name}`,
|
|
180
|
+
inputSchema: tool.parameters || { type: "object", properties: {} },
|
|
181
|
+
}));
|
|
182
|
+
console.error(`[mcp-server] list-tools: ${mcpTools.length} tools`);
|
|
183
|
+
return { tools: mcpTools };
|
|
184
|
+
});
|
|
185
|
+
|
|
186
|
+
// The context is built before the transport handshake so capability
|
|
187
|
+
// discovery can mutate it (Pitfall 4) before fireSessionStart() consumes it.
|
|
188
|
+
const ctx = {
|
|
189
|
+
cwd: process.cwd(),
|
|
190
|
+
hasUI: false,
|
|
191
|
+
mode: undefined as string | undefined,
|
|
192
|
+
ui: undefined as UISystem | undefined,
|
|
193
|
+
modelRegistry: undefined as unknown,
|
|
194
|
+
model: undefined as unknown,
|
|
195
|
+
signal: undefined as AbortSignal | undefined,
|
|
196
|
+
reload: undefined as (() => Promise<void>) | undefined,
|
|
197
|
+
samplingProvider: undefined as unknown,
|
|
198
|
+
};
|
|
199
|
+
|
|
200
|
+
server.setRequestHandler(CallToolRequestSchema, async (request) => {
|
|
201
|
+
const { name, arguments: callArgs } = request.params;
|
|
202
|
+
const tool = host.tools.get(name);
|
|
203
|
+
if (!tool) {
|
|
204
|
+
throw new Error(`Unknown tool: ${name}`);
|
|
205
|
+
}
|
|
206
|
+
try {
|
|
207
|
+
const result = await tool.execute(
|
|
208
|
+
`call-${Date.now()}`,
|
|
209
|
+
callArgs || {},
|
|
210
|
+
undefined,
|
|
211
|
+
undefined,
|
|
212
|
+
ctx,
|
|
213
|
+
);
|
|
214
|
+
// Upstream engine tools return MCP-shaped results ({ content: [...] });
|
|
215
|
+
// pass those through verbatim and stringify anything else.
|
|
216
|
+
if (result && typeof result === "object" && "content" in result) {
|
|
217
|
+
return result;
|
|
218
|
+
}
|
|
219
|
+
const text = typeof result === "string" ? result : JSON.stringify(result, null, 2);
|
|
220
|
+
return { content: [{ type: "text" as const, text }] };
|
|
221
|
+
} catch (err) {
|
|
222
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
223
|
+
return {
|
|
224
|
+
content: [{ type: "text" as const, text: `Error: ${message}` }],
|
|
225
|
+
isError: true,
|
|
226
|
+
};
|
|
227
|
+
}
|
|
228
|
+
});
|
|
229
|
+
|
|
230
|
+
// Step 7: CRITICAL — Connect transport BEFORE fireSessionStart (Pitfall 1)
|
|
231
|
+
const transport = new StdioServerTransport();
|
|
232
|
+
await server.connect(transport);
|
|
233
|
+
|
|
234
|
+
// Step 8: CRITICAL — Check client capabilities via getClientCapabilities() (Pitfall 5)
|
|
235
|
+
const clientCaps = server.getClientCapabilities();
|
|
236
|
+
|
|
237
|
+
// Step 9: If client declares sampling capability — inject ProtocolSamplingForwarder
|
|
238
|
+
// D-11: No config.settings.sampling check — pure forwarding.
|
|
239
|
+
if (clientCaps?.sampling) {
|
|
240
|
+
const samplingForwarder = new ProtocolSamplingForwarder(server);
|
|
241
|
+
ctx.samplingProvider = samplingForwarder;
|
|
242
|
+
// Pitfall 4: Set hasUI so init.ts sampling condition passes
|
|
243
|
+
ctx.hasUI = true;
|
|
244
|
+
console.error("[mcp-server] Sampling capability detected — ProtocolSamplingForwarder injected");
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
// Step 10: If client declares elicitation.form capability — inject ProtocolElicitationForwarder
|
|
248
|
+
// D-11: No config.settings.elicitation check — pure forwarding.
|
|
249
|
+
if (clientCaps?.elicitation?.form) {
|
|
250
|
+
const elicitationForwarder = new ProtocolElicitationForwarder(server);
|
|
251
|
+
const ui: UISystem = {
|
|
252
|
+
notify: (message: string, level: "info" | "warning" | "error"): void => {
|
|
253
|
+
const consoleMethod: "info" | "warn" | "error" =
|
|
254
|
+
level === "error" ? "error" : level === "warning" ? "warn" : "info";
|
|
255
|
+
console[consoleMethod](`[mcp-server] ${message}`);
|
|
256
|
+
},
|
|
257
|
+
form: (config: FormConfig) => elicitationForwarder.form(config),
|
|
258
|
+
};
|
|
259
|
+
ctx.ui = ui;
|
|
260
|
+
// Pitfall 4: Set hasUI so init.ts elicitation condition passes
|
|
261
|
+
ctx.hasUI = true;
|
|
262
|
+
console.error("[mcp-server] Elicitation.form capability detected — ProtocolElicitationForwarder injected");
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
// Step 11: Fire session_start — triggers initializeMcp which reads ctx
|
|
266
|
+
// with forwarders injected. T-12-11: wrap in try/catch, non-fatal.
|
|
267
|
+
try {
|
|
268
|
+
await host.fireSessionStart(ctx);
|
|
269
|
+
console.error("[mcp-server] Session started, lazy connections initialized");
|
|
270
|
+
} catch (err) {
|
|
271
|
+
console.error(`[mcp-server] Session start error: ${(err as Error).message}`);
|
|
272
|
+
// Non-fatal — servers connect lazily on first tool call
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
// Step 12: Server ready
|
|
276
|
+
console.error("[mcp-server] MCP server ready via stdio");
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
main().catch((err: unknown) => {
|
|
280
|
+
console.error(`[mcp-server] Fatal error: ${err instanceof Error ? err.message : String(err)}`);
|
|
281
|
+
process.exit(1);
|
|
282
|
+
});
|
package/cli.js
ADDED
|
@@ -0,0 +1,392 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
import fs from "node:fs";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
import os from "node:os";
|
|
6
|
+
import { pathToFileURL } from "node:url";
|
|
7
|
+
import stripJsonComments from "strip-json-comments";
|
|
8
|
+
|
|
9
|
+
const HOME = os.homedir();
|
|
10
|
+
|
|
11
|
+
function expandHome(input) {
|
|
12
|
+
if (input === "~") return HOME;
|
|
13
|
+
if (input.startsWith("~/")) return path.resolve(HOME, input.slice(2));
|
|
14
|
+
return path.resolve(input);
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
function readPiConfig() {
|
|
18
|
+
const dir = process.env.PI_PACKAGE_DIR?.trim();
|
|
19
|
+
if (!dir) return undefined;
|
|
20
|
+
try {
|
|
21
|
+
return JSON.parse(fs.readFileSync(path.join(path.resolve(dir), "package.json"), "utf8")).piConfig;
|
|
22
|
+
} catch {
|
|
23
|
+
return undefined;
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
function getConfigDirName() {
|
|
28
|
+
const configDir = readPiConfig()?.configDir;
|
|
29
|
+
return typeof configDir === "string" && configDir.trim() ? configDir.trim() : ".pi";
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function getAgentDir() {
|
|
33
|
+
const piConfig = readPiConfig();
|
|
34
|
+
const appName = typeof piConfig?.name === "string" && piConfig.name.trim() ? piConfig.name.trim() : "pi";
|
|
35
|
+
const configured = process.env[`${appName.toUpperCase()}_CODING_AGENT_DIR`]?.trim();
|
|
36
|
+
if (configured) return expandHome(configured);
|
|
37
|
+
return path.join(HOME, getConfigDirName(), "agent");
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
const AGENT_DIR = getAgentDir();
|
|
41
|
+
const PI_CONFIG_PATH = path.join(AGENT_DIR, "mcp.json");
|
|
42
|
+
const GENERIC_GLOBAL_CONFIG_PATH = path.join(HOME, ".config", "mcp", "mcp.json");
|
|
43
|
+
const AGENTS_GLOBAL_CONFIG_PATH = path.join(HOME, ".agents", "mcp.json");
|
|
44
|
+
const AGENTS_NESTED_GLOBAL_CONFIG_PATH = path.join(HOME, ".agents", "mcp", "mcp.json");
|
|
45
|
+
const PROJECT_CONFIG_PATH = path.resolve(process.cwd(), ".mcp.json");
|
|
46
|
+
const PROJECT_PI_CONFIG_PATH = path.resolve(process.cwd(), getConfigDirName(), "mcp.json");
|
|
47
|
+
|
|
48
|
+
const IMPORT_PATHS = {
|
|
49
|
+
cursor: [path.join(HOME, ".cursor", "mcp.json")],
|
|
50
|
+
"claude-code": [
|
|
51
|
+
path.join(HOME, ".claude", "mcp.json"),
|
|
52
|
+
path.join(HOME, ".claude.json"),
|
|
53
|
+
path.join(HOME, ".claude", "claude_desktop_config.json"),
|
|
54
|
+
],
|
|
55
|
+
"claude-desktop": [path.join(HOME, "Library", "Application Support", "Claude", "claude_desktop_config.json")],
|
|
56
|
+
codex: [
|
|
57
|
+
path.join(HOME, ".codex", "config.toml"),
|
|
58
|
+
path.join(HOME, ".codex", "config.json"),
|
|
59
|
+
],
|
|
60
|
+
opencode: [
|
|
61
|
+
path.join(HOME, ".config", "opencode", "opencode.json"),
|
|
62
|
+
path.resolve(process.cwd(), "opencode.json"),
|
|
63
|
+
],
|
|
64
|
+
windsurf: [path.join(HOME, ".windsurf", "mcp.json")],
|
|
65
|
+
vscode: [path.resolve(process.cwd(), ".vscode", "mcp.json")],
|
|
66
|
+
};
|
|
67
|
+
|
|
68
|
+
function printHelp(log = console.log) {
|
|
69
|
+
log("pi-mcp-adapter helper\n");
|
|
70
|
+
log("Install the package with:");
|
|
71
|
+
log(" pi install npm:pi-mcp-adapter\n");
|
|
72
|
+
log("Then optionally run:");
|
|
73
|
+
log(" pi-mcp-adapter init Detect host configs and scaffold Pi imports");
|
|
74
|
+
log(" pi-mcp-adapter init --dry-run");
|
|
75
|
+
log(" pi-mcp-adapter init --discover-host-configs Opt in to host config fallback discovery");
|
|
76
|
+
log("");
|
|
77
|
+
log("Bearer token storage (servers configured with auth: \"bearer\" and bearerTokenStore: true):");
|
|
78
|
+
log(" pi-mcp-adapter token set <server> Store a token read from stdin (masked prompt or pipe; never argv)");
|
|
79
|
+
log(" pi-mcp-adapter token status <server> Report whether a stored token matches the configured URL");
|
|
80
|
+
log(" pi-mcp-adapter token remove <server> Remove the stored token");
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
function readJsonFile(filePath) {
|
|
84
|
+
return JSON.parse(stripJsonComments(fs.readFileSync(filePath, "utf-8"), { trailingCommas: true }));
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
function loadPiConfig() {
|
|
88
|
+
if (!fs.existsSync(PI_CONFIG_PATH)) {
|
|
89
|
+
return { mcpServers: {} };
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
const raw = readJsonFile(PI_CONFIG_PATH);
|
|
93
|
+
const mcpServers = raw.mcpServers ?? raw["mcp-servers"] ?? {};
|
|
94
|
+
if (!mcpServers || typeof mcpServers !== "object" || Array.isArray(mcpServers)) {
|
|
95
|
+
throw new Error(`Invalid MCP config at ${PI_CONFIG_PATH}: expected \"mcpServers\" to be an object`);
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
const normalized = { ...raw };
|
|
99
|
+
delete normalized["mcp-servers"];
|
|
100
|
+
|
|
101
|
+
const imports = Array.isArray(raw.imports) ? raw.imports.filter((value) => typeof value === "string") : undefined;
|
|
102
|
+
return {
|
|
103
|
+
...normalized,
|
|
104
|
+
mcpServers,
|
|
105
|
+
imports,
|
|
106
|
+
};
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
function findAvailableImports() {
|
|
110
|
+
const found = [];
|
|
111
|
+
|
|
112
|
+
for (const [kind, candidates] of Object.entries(IMPORT_PATHS)) {
|
|
113
|
+
const existing = candidates.find((candidate) => fs.existsSync(candidate));
|
|
114
|
+
if (existing) {
|
|
115
|
+
found.push({ kind, path: existing });
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
return found;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
function printDiscovery(log, imports) {
|
|
123
|
+
log("Config discovery:\n");
|
|
124
|
+
|
|
125
|
+
const paths = [
|
|
126
|
+
["User-global standard MCP", GENERIC_GLOBAL_CONFIG_PATH],
|
|
127
|
+
["User-global .agents MCP", AGENTS_GLOBAL_CONFIG_PATH],
|
|
128
|
+
["User-global .agents nested MCP", AGENTS_NESTED_GLOBAL_CONFIG_PATH],
|
|
129
|
+
["Pi global override", PI_CONFIG_PATH],
|
|
130
|
+
["Project standard MCP", PROJECT_CONFIG_PATH],
|
|
131
|
+
["Project Pi override", PROJECT_PI_CONFIG_PATH],
|
|
132
|
+
];
|
|
133
|
+
|
|
134
|
+
for (const [label, filePath] of paths) {
|
|
135
|
+
const prefix = fs.existsSync(filePath) ? "✓" : "-";
|
|
136
|
+
log(`${prefix} ${label}: ${filePath}`);
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
log("\nCompatibility imports:\n");
|
|
140
|
+
if (imports.length === 0) {
|
|
141
|
+
log("- No host-specific MCP configs detected");
|
|
142
|
+
return;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
for (const entry of imports) {
|
|
146
|
+
log(`✓ ${entry.kind}: ${entry.path}`);
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
function writePiConfig(config) {
|
|
151
|
+
fs.mkdirSync(path.dirname(PI_CONFIG_PATH), { recursive: true });
|
|
152
|
+
fs.writeFileSync(PI_CONFIG_PATH, `${JSON.stringify(config, null, 2)}\n`, "utf-8");
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
async function runInit(argv, log = console.log) {
|
|
156
|
+
const dryRun = argv.includes("--dry-run");
|
|
157
|
+
const discoverHostConfigs = argv.includes("--discover-host-configs");
|
|
158
|
+
const foundImports = findAvailableImports();
|
|
159
|
+
const existingConfig = loadPiConfig();
|
|
160
|
+
const existingImports = new Set(existingConfig.imports ?? []);
|
|
161
|
+
const importsToAdd = foundImports
|
|
162
|
+
.map((entry) => entry.kind)
|
|
163
|
+
.filter((kind) => !existingImports.has(kind));
|
|
164
|
+
|
|
165
|
+
printDiscovery(log, foundImports);
|
|
166
|
+
|
|
167
|
+
const discoverySettingChanged = discoverHostConfigs && existingConfig.settings?.hostConfigDiscovery !== "on";
|
|
168
|
+
if (importsToAdd.length === 0 && !discoverySettingChanged) {
|
|
169
|
+
log("\nNo Pi config changes needed.");
|
|
170
|
+
log("Standard MCP configs are discovered automatically, and host-specific imports are already configured or unavailable.");
|
|
171
|
+
return 0;
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
const nextConfig = {
|
|
175
|
+
...existingConfig,
|
|
176
|
+
...(discoverySettingChanged ? { settings: { ...existingConfig.settings, hostConfigDiscovery: "on" } } : {}),
|
|
177
|
+
...(importsToAdd.length > 0 ? { imports: [...existingImports, ...importsToAdd] } : {}),
|
|
178
|
+
mcpServers: existingConfig.mcpServers ?? {},
|
|
179
|
+
};
|
|
180
|
+
|
|
181
|
+
if (importsToAdd.length > 0) {
|
|
182
|
+
log(`\nDetected host configs to import into Pi: ${importsToAdd.join(", ")}`);
|
|
183
|
+
}
|
|
184
|
+
if (discoverySettingChanged) {
|
|
185
|
+
log("Opting in to host-specific fallback discovery (standard and Pi-owned configs still take precedence).");
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
if (dryRun) {
|
|
189
|
+
log(`Dry run: would update ${PI_CONFIG_PATH}`);
|
|
190
|
+
return 0;
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
writePiConfig(nextConfig);
|
|
194
|
+
log(`Updated ${PI_CONFIG_PATH}`);
|
|
195
|
+
log("Pi will now keep reading standard MCP configs automatically, while these imports cover host-specific config formats.");
|
|
196
|
+
if (discoverySettingChanged) {
|
|
197
|
+
log("Host config discovery is explicit and does not write to or execute commands from external host files.");
|
|
198
|
+
}
|
|
199
|
+
return 0;
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
async function importTokenModules(error) {
|
|
203
|
+
try {
|
|
204
|
+
const [store, config, utils] = await Promise.all([
|
|
205
|
+
import("./mcp-bearer-store.ts"),
|
|
206
|
+
import("./config.ts"),
|
|
207
|
+
import("./utils.ts"),
|
|
208
|
+
]);
|
|
209
|
+
return { store, config, utils };
|
|
210
|
+
} catch (err) {
|
|
211
|
+
error("Token commands need a Node.js version that can load TypeScript modules (Node 22.18+ or 23+).");
|
|
212
|
+
error(`Import failed: ${err instanceof Error ? err.message : String(err)}`);
|
|
213
|
+
return undefined;
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
function readTokenFromStdin(stdin) {
|
|
218
|
+
if (stdin.isTTY) return readTokenMasked(stdin);
|
|
219
|
+
return new Promise((resolve, reject) => {
|
|
220
|
+
let data = "";
|
|
221
|
+
stdin.setEncoding("utf8");
|
|
222
|
+
stdin.on("data", (chunk) => {
|
|
223
|
+
data += chunk;
|
|
224
|
+
});
|
|
225
|
+
stdin.on("end", () => resolve(data.replace(/[\r\n]+$/, "")));
|
|
226
|
+
stdin.on("error", reject);
|
|
227
|
+
});
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
// Raw-mode masked prompt: the token never echoes to the terminal.
|
|
231
|
+
function readTokenMasked(stdin) {
|
|
232
|
+
return new Promise((resolve, reject) => {
|
|
233
|
+
process.stderr.write("Enter bearer token (input hidden): ");
|
|
234
|
+
stdin.setRawMode(true);
|
|
235
|
+
stdin.resume();
|
|
236
|
+
stdin.setEncoding("utf8");
|
|
237
|
+
let token = "";
|
|
238
|
+
const onData = (chunk) => {
|
|
239
|
+
for (const char of chunk) {
|
|
240
|
+
if (char === "\u0003") {
|
|
241
|
+
cleanup();
|
|
242
|
+
reject(new Error("Token entry cancelled"));
|
|
243
|
+
return;
|
|
244
|
+
}
|
|
245
|
+
if (char === "\r" || char === "\n") {
|
|
246
|
+
cleanup();
|
|
247
|
+
resolve(token);
|
|
248
|
+
return;
|
|
249
|
+
}
|
|
250
|
+
if (char === "\u007f" || char === "\b") {
|
|
251
|
+
token = token.slice(0, -1);
|
|
252
|
+
continue;
|
|
253
|
+
}
|
|
254
|
+
token += char;
|
|
255
|
+
}
|
|
256
|
+
};
|
|
257
|
+
const cleanup = () => {
|
|
258
|
+
stdin.setRawMode(false);
|
|
259
|
+
stdin.pause();
|
|
260
|
+
stdin.off("data", onData);
|
|
261
|
+
process.stderr.write("\n");
|
|
262
|
+
};
|
|
263
|
+
stdin.on("data", onData);
|
|
264
|
+
});
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
async function runToken(argv, log, error, stdin) {
|
|
268
|
+
const [action, serverName, ...extra] = argv;
|
|
269
|
+
if (!["set", "status", "remove"].includes(action) || !serverName) {
|
|
270
|
+
error("Usage: pi-mcp-adapter token <set|status|remove> <server>");
|
|
271
|
+
error("`token set` reads the token from stdin only. Never pass the token as an argument.");
|
|
272
|
+
return 1;
|
|
273
|
+
}
|
|
274
|
+
if (extra.length > 0) {
|
|
275
|
+
error("Unexpected extra arguments. The token must not be passed on the command line; pipe it on stdin or use the interactive prompt.");
|
|
276
|
+
return 1;
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
const modules = await importTokenModules(error);
|
|
280
|
+
if (!modules) return 1;
|
|
281
|
+
|
|
282
|
+
// Argv-derived text is sanitized before terminal output, and the resolved
|
|
283
|
+
// URL is never printed: it can embed userinfo or interpolated secrets.
|
|
284
|
+
const safeName = modules.utils.sanitizeTerminalText(serverName);
|
|
285
|
+
const definition = modules.config.loadMcpConfig(undefined, process.cwd()).mcpServers[serverName];
|
|
286
|
+
if (!definition) {
|
|
287
|
+
error(`Server "${safeName}" not found in the effective MCP config.`);
|
|
288
|
+
return 1;
|
|
289
|
+
}
|
|
290
|
+
if (definition.auth !== "bearer" || definition.bearerTokenStore !== true) {
|
|
291
|
+
error(`Server "${safeName}" is not configured for bearerTokenStore. Set "auth": "bearer" and "bearerTokenStore": true.`);
|
|
292
|
+
return 1;
|
|
293
|
+
}
|
|
294
|
+
// resolveServerUrl embeds the interpolated URL in its exceptions, so catch
|
|
295
|
+
// and redact: the URL can carry userinfo or interpolated secrets.
|
|
296
|
+
let serverUrl;
|
|
297
|
+
try {
|
|
298
|
+
serverUrl = modules.utils.resolveServerUrl(definition);
|
|
299
|
+
} catch {
|
|
300
|
+
error(`Server "${safeName}" has an invalid or unresolvable URL. Fix the server's url in the MCP config and retry.`);
|
|
301
|
+
return 1;
|
|
302
|
+
}
|
|
303
|
+
if (!serverUrl) {
|
|
304
|
+
error(`Server "${safeName}" has no URL configured.`);
|
|
305
|
+
return 1;
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
if (action === "set") {
|
|
309
|
+
const token = await readTokenFromStdin(stdin);
|
|
310
|
+
if (!token) {
|
|
311
|
+
error("No token provided on stdin.");
|
|
312
|
+
return 1;
|
|
313
|
+
}
|
|
314
|
+
try {
|
|
315
|
+
modules.store.saveBearerTokenForUrl(serverName, token, serverUrl);
|
|
316
|
+
} catch (err) {
|
|
317
|
+
error(modules.utils.sanitizeTerminalText(err instanceof Error ? err.message : String(err)));
|
|
318
|
+
return 1;
|
|
319
|
+
}
|
|
320
|
+
log(`Bearer token stored for "${safeName}" and bound to the configured server URL.`);
|
|
321
|
+
if (definition.bearerToken !== undefined || definition.bearerTokenEnv !== undefined) {
|
|
322
|
+
log("Note: this server also configures bearerToken or bearerTokenEnv, which take precedence over the stored token.");
|
|
323
|
+
}
|
|
324
|
+
return 0;
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
if (action === "status") {
|
|
328
|
+
const status = modules.store.inspectBearerTokenForUrl(serverName, serverUrl);
|
|
329
|
+
if (status.status === "present") {
|
|
330
|
+
log(`Bearer token is stored for "${safeName}".`);
|
|
331
|
+
return 0;
|
|
332
|
+
}
|
|
333
|
+
if (status.status === "url-mismatch") {
|
|
334
|
+
log(`Bearer token is stored for "${safeName}", but its URL does not match the current server URL. Run \`pi-mcp-adapter token set ${safeName}\` to rebind it.`);
|
|
335
|
+
return 1;
|
|
336
|
+
}
|
|
337
|
+
if (status.status === "unavailable") {
|
|
338
|
+
error(status.message);
|
|
339
|
+
return 1;
|
|
340
|
+
}
|
|
341
|
+
log(`No bearer token is stored for "${safeName}".`);
|
|
342
|
+
return 1;
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
try {
|
|
346
|
+
modules.store.removeBearerToken(serverName);
|
|
347
|
+
} catch (err) {
|
|
348
|
+
error(modules.utils.sanitizeTerminalText(err instanceof Error ? err.message : String(err)));
|
|
349
|
+
return 1;
|
|
350
|
+
}
|
|
351
|
+
log(`Bearer token removed for "${safeName}".`);
|
|
352
|
+
return 0;
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
export async function main(argv = process.argv.slice(2), log = console.log, error = console.error, stdin = process.stdin) {
|
|
356
|
+
const [command, ...rest] = argv;
|
|
357
|
+
|
|
358
|
+
if (!command || command === "help" || command === "--help" || command === "-h") {
|
|
359
|
+
printHelp(log);
|
|
360
|
+
return 0;
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
if (command === "token") {
|
|
364
|
+
return runToken(rest, log, error, stdin);
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
if (command === "install") {
|
|
368
|
+
error("The custom downloader has been retired.");
|
|
369
|
+
error("Use `pi install npm:pi-mcp-adapter` instead, then optionally run `pi-mcp-adapter init`.");
|
|
370
|
+
return 1;
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
if (command === "init") {
|
|
374
|
+
return runInit(rest, log);
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
error(`Unknown command: ${command}`);
|
|
378
|
+
printHelp(log);
|
|
379
|
+
return 1;
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
const resolvedEntrypoint = process.argv[1] ? fs.realpathSync(process.argv[1]) : undefined;
|
|
383
|
+
const isEntrypoint = resolvedEntrypoint && import.meta.url === pathToFileURL(resolvedEntrypoint).href;
|
|
384
|
+
|
|
385
|
+
if (isEntrypoint) {
|
|
386
|
+
main().then((code) => {
|
|
387
|
+
process.exitCode = code;
|
|
388
|
+
}).catch((err) => {
|
|
389
|
+
console.error(`\nHelper failed: ${err instanceof Error ? err.message : String(err)}`);
|
|
390
|
+
process.exit(1);
|
|
391
|
+
});
|
|
392
|
+
}
|