@fitchmultz/pi-mcp-adapter 5.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +750 -0
- package/LICENSE +21 -0
- package/OAUTH.md +462 -0
- package/README.md +820 -0
- package/abort.ts +34 -0
- package/agent-dir.ts +24 -0
- package/app-bridge.bundle.js +67 -0
- package/banner.png +0 -0
- package/checkpoint.ts +55 -0
- package/cli.js +222 -0
- package/commands.ts +619 -0
- package/config.ts +1204 -0
- package/consent-manager.ts +25 -0
- package/direct-tools.ts +408 -0
- package/dist/abort.d.ts +2 -0
- package/dist/abort.js +35 -0
- package/dist/agent-dir.d.ts +3 -0
- package/dist/agent-dir.js +21 -0
- package/dist/app-bridge.bundle.js +67 -0
- package/dist/checkpoint.d.ts +18 -0
- package/dist/checkpoint.js +53 -0
- package/dist/commands.d.ts +20 -0
- package/dist/commands.js +521 -0
- package/dist/config.d.ts +109 -0
- package/dist/config.js +1013 -0
- package/dist/consent-manager.d.ts +8 -0
- package/dist/consent-manager.js +21 -0
- package/dist/direct-tools.d.ts +10 -0
- package/dist/direct-tools.js +350 -0
- package/dist/docs/client-metadata.json +14 -0
- package/dist/elicitation-handler.d.ts +17 -0
- package/dist/elicitation-handler.js +308 -0
- package/dist/error-signal.d.ts +15 -0
- package/dist/error-signal.js +21 -0
- package/dist/glimpse-ui.d.ts +9 -0
- package/dist/glimpse-ui.js +75 -0
- package/dist/host-html-template.d.ts +15 -0
- package/dist/host-html-template.js +429 -0
- package/dist/index.d.ts +7 -0
- package/dist/index.js +840 -0
- package/dist/init.d.ts +25 -0
- package/dist/init.js +562 -0
- package/dist/legacy-migration.d.ts +18 -0
- package/dist/legacy-migration.js +45 -0
- package/dist/lifecycle.d.ts +40 -0
- package/dist/lifecycle.js +167 -0
- package/dist/logger.d.ts +38 -0
- package/dist/logger.js +102 -0
- package/dist/mcp-auth-flow.d.ts +113 -0
- package/dist/mcp-auth-flow.js +834 -0
- package/dist/mcp-auth.d.ts +127 -0
- package/dist/mcp-auth.js +658 -0
- package/dist/mcp-callback-server.d.ts +56 -0
- package/dist/mcp-callback-server.js +371 -0
- package/dist/mcp-code.d.ts +51 -0
- package/dist/mcp-code.js +366 -0
- package/dist/mcp-keyring-helper.cjs +89 -0
- package/dist/mcp-oauth-provider.d.ts +154 -0
- package/dist/mcp-oauth-provider.js +672 -0
- package/dist/mcp-output-guard.d.ts +59 -0
- package/dist/mcp-output-guard.js +332 -0
- package/dist/mcp-panel.d.ts +66 -0
- package/dist/mcp-panel.js +889 -0
- package/dist/mcp-script-worker.mjs +128 -0
- package/dist/mcp-setup-panel.d.ts +84 -0
- package/dist/mcp-setup-panel.js +561 -0
- package/dist/mcp-status.d.ts +11 -0
- package/dist/mcp-status.js +96 -0
- package/dist/mcp-trace.d.ts +95 -0
- package/dist/mcp-trace.js +233 -0
- package/dist/metadata-cache.d.ts +18 -0
- package/dist/metadata-cache.js +277 -0
- package/dist/npx-resolver.d.ts +6 -0
- package/dist/npx-resolver.js +448 -0
- package/dist/onboarding-state.d.ts +11 -0
- package/dist/onboarding-state.js +47 -0
- package/dist/panel-keys.d.ts +16 -0
- package/dist/panel-keys.js +15 -0
- package/dist/prompts.d.ts +56 -0
- package/dist/prompts.js +284 -0
- package/dist/proxy-modes.d.ts +38 -0
- package/dist/proxy-modes.js +1235 -0
- package/dist/resource-tools.d.ts +1 -0
- package/dist/resource-tools.js +14 -0
- package/dist/runtime-owner.d.ts +18 -0
- package/dist/runtime-owner.js +117 -0
- package/dist/sampling-handler.d.ts +15 -0
- package/dist/sampling-handler.js +211 -0
- package/dist/search-ranking.d.ts +20 -0
- package/dist/search-ranking.js +180 -0
- package/dist/server-manager.d.ts +114 -0
- package/dist/server-manager.js +1175 -0
- package/dist/session-recovery.d.ts +31 -0
- package/dist/session-recovery.js +310 -0
- package/dist/state.d.ts +63 -0
- package/dist/state.js +1 -0
- package/dist/tool-approval.d.ts +10 -0
- package/dist/tool-approval.js +42 -0
- package/dist/tool-metadata.d.ts +9 -0
- package/dist/tool-metadata.js +193 -0
- package/dist/tool-registrar.d.ts +10 -0
- package/dist/tool-registrar.js +64 -0
- package/dist/tool-result-renderer.d.ts +45 -0
- package/dist/tool-result-renderer.js +224 -0
- package/dist/ts-shape.d.ts +2 -0
- package/dist/ts-shape.js +147 -0
- package/dist/types.d.ts +516 -0
- package/dist/types.js +168 -0
- package/dist/ui-resource-handler.d.ts +17 -0
- package/dist/ui-resource-handler.js +209 -0
- package/dist/ui-server.d.ts +51 -0
- package/dist/ui-server.js +669 -0
- package/dist/ui-session.d.ts +39 -0
- package/dist/ui-session.js +463 -0
- package/dist/ui-stream-types.d.ts +104 -0
- package/dist/ui-stream-types.js +58 -0
- package/dist/ui-tool-visibility.d.ts +4 -0
- package/dist/ui-tool-visibility.js +26 -0
- package/dist/unix-socket-transport.d.ts +15 -0
- package/dist/unix-socket-transport.js +84 -0
- package/dist/utils.d.ts +30 -0
- package/dist/utils.js +276 -0
- package/docs/client-metadata.json +14 -0
- package/elicitation-handler.ts +349 -0
- package/error-signal.ts +21 -0
- package/glimpse-ui.ts +80 -0
- package/host-html-template.ts +456 -0
- package/index.ts +900 -0
- package/init.ts +627 -0
- package/legacy-migration.ts +47 -0
- package/lifecycle.ts +165 -0
- package/logger.ts +127 -0
- package/mcp-auth-flow.ts +975 -0
- package/mcp-auth.ts +793 -0
- package/mcp-callback-server.ts +450 -0
- package/mcp-code.ts +386 -0
- package/mcp-keyring-helper.cjs +89 -0
- package/mcp-oauth-provider.ts +774 -0
- package/mcp-output-guard.ts +412 -0
- package/mcp-panel.ts +978 -0
- package/mcp-script-worker.mjs +128 -0
- package/mcp-setup-panel.ts +666 -0
- package/mcp-status.ts +109 -0
- package/mcp-trace.ts +295 -0
- package/metadata-cache.ts +333 -0
- package/npx-resolver.ts +488 -0
- package/onboarding-state.ts +58 -0
- package/package.json +182 -0
- package/panel-keys.ts +37 -0
- package/prompts.ts +337 -0
- package/proxy-modes.ts +1361 -0
- package/resource-tools.ts +17 -0
- package/runtime-owner.ts +123 -0
- package/sampling-handler.ts +273 -0
- package/scripts/build.mjs +131 -0
- package/scripts/prepare.mjs +102 -0
- package/search-ranking.ts +196 -0
- package/server-manager.ts +1320 -0
- package/session-recovery.ts +316 -0
- package/skills/mcp-scripting/SKILL.md +38 -0
- package/state.ts +64 -0
- package/tool-approval.ts +78 -0
- package/tool-metadata.ts +235 -0
- package/tool-registrar.ts +69 -0
- package/tool-result-renderer.ts +286 -0
- package/ts-shape.ts +145 -0
- package/tsconfig.build.json +13 -0
- package/tsconfig.json +16 -0
- package/types.ts +810 -0
- package/ui-resource-handler.ts +249 -0
- package/ui-server.ts +808 -0
- package/ui-session.ts +568 -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 +309 -0
package/tool-metadata.ts
ADDED
|
@@ -0,0 +1,235 @@
|
|
|
1
|
+
import { getToolUiResourceUri } from "@modelcontextprotocol/ext-apps/app-bridge";
|
|
2
|
+
import type { McpExtensionState } from "./state.ts";
|
|
3
|
+
import type { ToolMetadata, McpTool, McpResource, ServerEntry, ToolPrefix } from "./types.ts";
|
|
4
|
+
import { formatToolName, isToolAllowed, resolveToolPrefix } from "./types.ts";
|
|
5
|
+
import { resourceNameToToolName } from "./resource-tools.ts";
|
|
6
|
+
import { extractToolUiStreamMode } from "./utils.ts";
|
|
7
|
+
import { extractUiToolVisibility, isUiToolVisibleToModel } from "./ui-tool-visibility.ts";
|
|
8
|
+
|
|
9
|
+
export function buildToolMetadata(
|
|
10
|
+
tools: McpTool[],
|
|
11
|
+
resources: McpResource[],
|
|
12
|
+
definition: ServerEntry,
|
|
13
|
+
serverName: string,
|
|
14
|
+
prefix: ToolPrefix
|
|
15
|
+
): { metadata: ToolMetadata[]; failedTools: string[] } {
|
|
16
|
+
const metadata: ToolMetadata[] = [];
|
|
17
|
+
const failedTools: string[] = [];
|
|
18
|
+
const seenNames = new Set<string>();
|
|
19
|
+
const effectivePrefix = resolveToolPrefix(definition, prefix);
|
|
20
|
+
|
|
21
|
+
for (const tool of tools) {
|
|
22
|
+
if (!tool?.name) {
|
|
23
|
+
failedTools.push("(unnamed)");
|
|
24
|
+
continue;
|
|
25
|
+
}
|
|
26
|
+
if (!isToolAllowed(tool.name, serverName, effectivePrefix, definition.includeTools, definition.excludeTools)) {
|
|
27
|
+
continue;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
const name = formatToolName(tool.name, serverName, effectivePrefix);
|
|
31
|
+
if (seenNames.has(name)) {
|
|
32
|
+
continue;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
const uiVisibility = extractUiToolVisibility(tool._meta);
|
|
36
|
+
if (!isUiToolVisibleToModel(uiVisibility)) {
|
|
37
|
+
continue;
|
|
38
|
+
}
|
|
39
|
+
seenNames.add(name);
|
|
40
|
+
|
|
41
|
+
let uiResourceUri: string | undefined;
|
|
42
|
+
try {
|
|
43
|
+
uiResourceUri = getToolUiResourceUri({ _meta: tool._meta });
|
|
44
|
+
} catch {
|
|
45
|
+
failedTools.push(tool.name);
|
|
46
|
+
}
|
|
47
|
+
const uiStreamMode = extractToolUiStreamMode(tool._meta);
|
|
48
|
+
metadata.push({
|
|
49
|
+
name,
|
|
50
|
+
originalName: tool.name,
|
|
51
|
+
description: tool.description ?? "",
|
|
52
|
+
...(tool.inputSchema !== undefined ? { inputSchema: tool.inputSchema } : {}),
|
|
53
|
+
...(tool.annotations !== undefined ? { annotations: tool.annotations } : {}),
|
|
54
|
+
...(uiResourceUri !== undefined ? { uiResourceUri } : {}),
|
|
55
|
+
...(uiVisibility !== undefined ? { uiVisibility } : {}),
|
|
56
|
+
...(uiStreamMode !== undefined ? { uiStreamMode } : {}),
|
|
57
|
+
});
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
if (definition.exposeResources !== false) {
|
|
61
|
+
for (const resource of resources) {
|
|
62
|
+
const baseName = `read_${resourceNameToToolName(resource.name)}`;
|
|
63
|
+
if (!isToolAllowed(baseName, serverName, effectivePrefix, definition.includeTools, definition.excludeTools)) {
|
|
64
|
+
continue;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
const name = formatToolName(baseName, serverName, effectivePrefix);
|
|
68
|
+
if (seenNames.has(name)) {
|
|
69
|
+
continue;
|
|
70
|
+
}
|
|
71
|
+
seenNames.add(name);
|
|
72
|
+
|
|
73
|
+
metadata.push({
|
|
74
|
+
name,
|
|
75
|
+
originalName: baseName,
|
|
76
|
+
description: resource.description ?? `Read resource: ${resource.uri}`,
|
|
77
|
+
resourceUri: resource.uri,
|
|
78
|
+
});
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
return { metadata, failedTools };
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
export function totalToolCount(state: McpExtensionState): number {
|
|
86
|
+
let count = 0;
|
|
87
|
+
for (const metadata of state.toolMetadata.values()) {
|
|
88
|
+
count += metadata.length;
|
|
89
|
+
}
|
|
90
|
+
return count;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
export function findToolByName(metadata: ToolMetadata[] | undefined, toolName: string): ToolMetadata | undefined {
|
|
94
|
+
if (!metadata) return undefined;
|
|
95
|
+
const exact = metadata.find(m => m.name === toolName);
|
|
96
|
+
if (exact) return exact;
|
|
97
|
+
const normalized = toolName.replace(/-/g, "_");
|
|
98
|
+
return metadata.find(m => m.name.replace(/-/g, "_") === normalized);
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
export function formatSchema(schema: unknown, indent = " "): string {
|
|
102
|
+
if (!schema || typeof schema !== "object" || Array.isArray(schema)) {
|
|
103
|
+
return `${indent}(no schema)`;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
const s = schema as Record<string, unknown>;
|
|
107
|
+
|
|
108
|
+
if (s.type === "object" && s.properties && typeof s.properties === "object" && !Array.isArray(s.properties)) {
|
|
109
|
+
const props = s.properties as Record<string, unknown>;
|
|
110
|
+
const required = Array.isArray(s.required) ? s.required.filter((name): name is string => typeof name === "string") : [];
|
|
111
|
+
|
|
112
|
+
if (Object.keys(props).length === 0) {
|
|
113
|
+
return `${indent}(no parameters)`;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
const lines: string[] = [];
|
|
117
|
+
for (const [name, propSchema] of Object.entries(props)) {
|
|
118
|
+
lines.push(...formatProperty(name, propSchema, required.includes(name), indent));
|
|
119
|
+
}
|
|
120
|
+
return lines.join("\n");
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
const lines = formatNestedSchema(s, indent);
|
|
124
|
+
if (lines.length > 0) {
|
|
125
|
+
return lines.join("\n");
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
const typeStr = formatType(s);
|
|
129
|
+
if (typeStr) {
|
|
130
|
+
return `${indent}(${typeStr})`;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
return `${indent}(complex schema)`;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
function formatProperty(name: string, schema: unknown, required: boolean, indent: string): string[] {
|
|
137
|
+
if (!schema || typeof schema !== "object" || Array.isArray(schema)) {
|
|
138
|
+
return [`${indent}${name}${required ? " *required*" : ""}`];
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
const s = schema as Record<string, unknown>;
|
|
142
|
+
const parts = [`${indent}${name}`];
|
|
143
|
+
const typeStr = formatType(s);
|
|
144
|
+
if (typeStr) parts.push(`(${typeStr})`);
|
|
145
|
+
if (required) parts.push("*required*");
|
|
146
|
+
appendSchemaAnnotations(parts, s);
|
|
147
|
+
|
|
148
|
+
return [parts.join(" "), ...formatNestedSchema(s, `${indent} `)];
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
function formatNestedSchema(schema: Record<string, unknown>, indent: string): string[] {
|
|
152
|
+
const lines: string[] = [];
|
|
153
|
+
|
|
154
|
+
if (Array.isArray(schema.anyOf)) {
|
|
155
|
+
lines.push(...formatVariants("anyOf", schema.anyOf, indent));
|
|
156
|
+
}
|
|
157
|
+
if (Array.isArray(schema.oneOf)) {
|
|
158
|
+
lines.push(...formatVariants("oneOf", schema.oneOf, indent));
|
|
159
|
+
}
|
|
160
|
+
if (schema.items !== undefined) {
|
|
161
|
+
lines.push(...formatProperty("items", schema.items, false, indent));
|
|
162
|
+
}
|
|
163
|
+
if (schema.properties && typeof schema.properties === "object" && !Array.isArray(schema.properties)) {
|
|
164
|
+
const required = Array.isArray(schema.required) ? schema.required.filter((name): name is string => typeof name === "string") : [];
|
|
165
|
+
for (const [name, propSchema] of Object.entries(schema.properties as Record<string, unknown>)) {
|
|
166
|
+
lines.push(...formatProperty(name, propSchema, required.includes(name), indent));
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
return lines;
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
function formatVariants(keyword: "anyOf" | "oneOf", variants: unknown[], indent: string): string[] {
|
|
174
|
+
const lines = [`${indent}${keyword}:`];
|
|
175
|
+
|
|
176
|
+
for (const variant of variants) {
|
|
177
|
+
if (!variant || typeof variant !== "object" || Array.isArray(variant)) {
|
|
178
|
+
lines.push(`${indent} - ${JSON.stringify(variant)}`);
|
|
179
|
+
continue;
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
const s = variant as Record<string, unknown>;
|
|
183
|
+
const typeStr = formatType(s) || "schema";
|
|
184
|
+
const parts = [`${indent} - ${typeStr}`];
|
|
185
|
+
appendSchemaAnnotations(parts, s);
|
|
186
|
+
lines.push(parts.join(" "));
|
|
187
|
+
lines.push(...formatNestedSchema(s, `${indent} `));
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
return lines;
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
function formatType(schema: Record<string, unknown>): string {
|
|
194
|
+
if (Object.hasOwn(schema, "const")) {
|
|
195
|
+
return `const ${JSON.stringify(schema.const)}`;
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
if (Array.isArray(schema.enum)) {
|
|
199
|
+
return `enum: ${schema.enum.map(v => JSON.stringify(v)).join(", ")}`;
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
if (Array.isArray(schema.type)) {
|
|
203
|
+
return schema.type.map(type => String(type)).join(" | ");
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
if (schema.type) {
|
|
207
|
+
return String(schema.type);
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
if (schema.properties && typeof schema.properties === "object" && !Array.isArray(schema.properties)) {
|
|
211
|
+
return "object";
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
if (schema.items !== undefined) {
|
|
215
|
+
return "array";
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
return "";
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
function appendSchemaAnnotations(parts: string[], schema: Record<string, unknown>): void {
|
|
222
|
+
if (schema.description && typeof schema.description === "string") {
|
|
223
|
+
parts.push(`- ${schema.description}`);
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
for (const key of ["minLength", "maxLength", "minimum", "maximum", "minItems", "maxItems", "format", "pattern"] as const) {
|
|
227
|
+
if (schema[key] !== undefined) {
|
|
228
|
+
parts.push(`[${key}: ${JSON.stringify(schema[key])}]`);
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
if (schema.default !== undefined) {
|
|
233
|
+
parts.push(`[default: ${JSON.stringify(schema.default)}]`);
|
|
234
|
+
}
|
|
235
|
+
}
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
// tool-registrar.ts - MCP content transformation
|
|
2
|
+
// NOTE: Tools are NOT registered with Pi - only the unified `mcp` proxy tool is registered.
|
|
3
|
+
// This keeps the LLM context small (1 tool instead of 100s).
|
|
4
|
+
|
|
5
|
+
import type { McpContent, ContentBlock } from "./types.ts";
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Transform MCP content types to Pi content blocks.
|
|
9
|
+
*/
|
|
10
|
+
export function transformMcpContent(content: McpContent[]): ContentBlock[] {
|
|
11
|
+
return content.map(c => {
|
|
12
|
+
if (c.type === "text") {
|
|
13
|
+
return { type: "text" as const, text: c.text ?? "" };
|
|
14
|
+
}
|
|
15
|
+
if (c.type === "image") {
|
|
16
|
+
return {
|
|
17
|
+
type: "image" as const,
|
|
18
|
+
data: c.data ?? "",
|
|
19
|
+
mimeType: c.mimeType ?? "image/png",
|
|
20
|
+
};
|
|
21
|
+
}
|
|
22
|
+
if (c.type === "resource") {
|
|
23
|
+
const resourceUri = c.resource?.uri ?? "(no URI)";
|
|
24
|
+
const resourceContent = c.resource?.text ?? (c.resource ? JSON.stringify(c.resource) : "(no content)");
|
|
25
|
+
return {
|
|
26
|
+
type: "text" as const,
|
|
27
|
+
text: `[Resource: ${resourceUri}]\n${resourceContent}`,
|
|
28
|
+
};
|
|
29
|
+
}
|
|
30
|
+
if (c.type === "resource_link") {
|
|
31
|
+
const linkName = c.name ?? c.uri ?? "unknown";
|
|
32
|
+
const linkUri = c.uri ?? "(no URI)";
|
|
33
|
+
return {
|
|
34
|
+
type: "text" as const,
|
|
35
|
+
text: `[Resource Link: ${linkName}]\nURI: ${linkUri}`,
|
|
36
|
+
};
|
|
37
|
+
}
|
|
38
|
+
if (c.type === "audio") {
|
|
39
|
+
return {
|
|
40
|
+
type: "text" as const,
|
|
41
|
+
text: `[Audio content: ${c.mimeType ?? "audio/*"}]`,
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
return { type: "text" as const, text: JSON.stringify(c) };
|
|
45
|
+
});
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* Resolve a tool result's content blocks, falling back to structuredContent
|
|
50
|
+
* when content is empty.
|
|
51
|
+
*/
|
|
52
|
+
export function resolveMcpResultContent(result: Record<string, unknown>): ContentBlock[] {
|
|
53
|
+
const blocks = transformMcpContent((Array.isArray(result.content) ? result.content : []) as McpContent[]);
|
|
54
|
+
if (blocks.length > 0) return blocks;
|
|
55
|
+
|
|
56
|
+
if (result.structuredContent !== undefined) {
|
|
57
|
+
return [{ type: "text" as const, text: stringifyStructuredContent(result.structuredContent) }];
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
return [];
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
function stringifyStructuredContent(value: unknown): string {
|
|
64
|
+
try {
|
|
65
|
+
return JSON.stringify(value, null, 2) ?? String(value);
|
|
66
|
+
} catch {
|
|
67
|
+
return String(value);
|
|
68
|
+
}
|
|
69
|
+
}
|
|
@@ -0,0 +1,286 @@
|
|
|
1
|
+
import { keyHint, type AgentToolResult, type Theme, type ToolRenderResultOptions } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import { type Component, Text } from "@earendil-works/pi-tui";
|
|
3
|
+
|
|
4
|
+
type McpToolResultDetails = Record<string, unknown> & { error?: unknown };
|
|
5
|
+
type McpToolContentBlock = AgentToolResult<McpToolResultDetails>["content"][number];
|
|
6
|
+
|
|
7
|
+
type RenderTheme = Pick<Theme, "fg" | "bold">;
|
|
8
|
+
|
|
9
|
+
const plainTheme: RenderTheme = {
|
|
10
|
+
fg: (_name, text) => text,
|
|
11
|
+
bold: (text) => text,
|
|
12
|
+
};
|
|
13
|
+
|
|
14
|
+
export interface McpProxyToolCallInput {
|
|
15
|
+
tool?: string;
|
|
16
|
+
args?: string | object;
|
|
17
|
+
connect?: string;
|
|
18
|
+
describe?: string;
|
|
19
|
+
search?: string;
|
|
20
|
+
includeSchemas?: boolean;
|
|
21
|
+
server?: string;
|
|
22
|
+
action?: string;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
interface McpToolRenderContext {
|
|
26
|
+
isError: boolean;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export interface McpToolResultDisplay {
|
|
30
|
+
lines: string[];
|
|
31
|
+
truncated: boolean;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
const DEFAULT_MAX_CALL_INPUT_CHARS = 1500;
|
|
35
|
+
const DEFAULT_MAX_COLLAPSED_LINES = 3;
|
|
36
|
+
const DEFAULT_MAX_COLLAPSED_CHARS = 8000;
|
|
37
|
+
const COLLAPSED_RENDER_CHAR_SLACK = 8;
|
|
38
|
+
|
|
39
|
+
class CollapsibleText implements Component {
|
|
40
|
+
private readonly fullText: Text;
|
|
41
|
+
private readonly footerText: Text;
|
|
42
|
+
private collapsedText: { charBudget: number; fullyIncluded: boolean; text: Text } | null = null;
|
|
43
|
+
|
|
44
|
+
constructor(
|
|
45
|
+
private readonly text: string,
|
|
46
|
+
private readonly expanded: boolean,
|
|
47
|
+
private readonly maxCollapsedLines: number,
|
|
48
|
+
private readonly ellipsis: string,
|
|
49
|
+
private readonly expandHint: string,
|
|
50
|
+
private readonly preTruncated = false,
|
|
51
|
+
) {
|
|
52
|
+
this.fullText = new Text(text, 0, 0);
|
|
53
|
+
this.footerText = new Text(`${ellipsis}\n${expandHint}`, 0, 0);
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
render(width: number): string[] {
|
|
57
|
+
if (this.expanded) {
|
|
58
|
+
return this.fullText.render(width);
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
const safeWidth = Math.max(1, Math.floor(width));
|
|
62
|
+
const charBudget = safeWidth * (this.maxCollapsedLines + 1) * COLLAPSED_RENDER_CHAR_SLACK;
|
|
63
|
+
if (!this.collapsedText || this.collapsedText.charBudget !== charBudget) {
|
|
64
|
+
const prefix = this.text.length > charBudget
|
|
65
|
+
? this.text.slice(0, charBudget)
|
|
66
|
+
: this.text;
|
|
67
|
+
this.collapsedText = {
|
|
68
|
+
charBudget,
|
|
69
|
+
fullyIncluded: prefix === this.text,
|
|
70
|
+
text: new Text(prefix, 0, 0),
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
const lines = this.collapsedText.text.render(width);
|
|
75
|
+
if (!this.preTruncated && this.collapsedText.fullyIncluded && lines.length <= this.maxCollapsedLines) return lines;
|
|
76
|
+
|
|
77
|
+
return [
|
|
78
|
+
...lines.slice(0, this.maxCollapsedLines),
|
|
79
|
+
...this.footerText.render(width),
|
|
80
|
+
];
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
invalidate(): void {}
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
function truncateText(value: string, maxChars: number): string {
|
|
87
|
+
if (value.length <= maxChars) return value;
|
|
88
|
+
return `${value.slice(0, Math.max(0, maxChars - 1))}…`;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
function formatJsonish(value: unknown, maxChars: number): string {
|
|
92
|
+
if (typeof value === "string") {
|
|
93
|
+
try {
|
|
94
|
+
return truncateText(JSON.stringify(JSON.parse(value), null, 2), maxChars);
|
|
95
|
+
} catch {
|
|
96
|
+
return truncateText(value, maxChars);
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
try {
|
|
101
|
+
return truncateText(JSON.stringify(value, null, 2), maxChars);
|
|
102
|
+
} catch {
|
|
103
|
+
return truncateText(String(value), maxChars);
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
function hasUsefulObjectContent(value: unknown): boolean {
|
|
108
|
+
return typeof value === "object" && value !== null && !Array.isArray(value) && Object.keys(value).length > 0;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
export function formatMcpProxyToolCallLines(
|
|
112
|
+
args: McpProxyToolCallInput,
|
|
113
|
+
maxInputChars = DEFAULT_MAX_CALL_INPUT_CHARS,
|
|
114
|
+
): string[] {
|
|
115
|
+
if (args.action === "ui-messages") return [`mcp ${args.action}`];
|
|
116
|
+
|
|
117
|
+
if (args.tool) {
|
|
118
|
+
const target = args.server ? `${args.tool} @ ${args.server}` : args.tool;
|
|
119
|
+
const lines = [`mcp call ${target}`];
|
|
120
|
+
if (args.args) lines.push(formatJsonish(args.args, maxInputChars));
|
|
121
|
+
return lines;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
if (args.connect) return [`mcp connect ${args.connect}`];
|
|
125
|
+
if (args.describe) return [`mcp describe ${args.describe}`];
|
|
126
|
+
|
|
127
|
+
if (args.search) {
|
|
128
|
+
let line = `mcp search ${args.search}`;
|
|
129
|
+
if (args.server) line += ` @ ${args.server}`;
|
|
130
|
+
if (args.includeSchemas === false) line += " (schemas hidden)";
|
|
131
|
+
return [line];
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
if (args.server) return [`mcp list ${args.server}`];
|
|
135
|
+
if (args.action) return [`mcp ${args.action}`];
|
|
136
|
+
|
|
137
|
+
return ["mcp status"];
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
export function formatMcpDirectToolCallLines(
|
|
141
|
+
displayName: string,
|
|
142
|
+
args: Record<string, unknown>,
|
|
143
|
+
maxInputChars = DEFAULT_MAX_CALL_INPUT_CHARS,
|
|
144
|
+
): string[] {
|
|
145
|
+
if (!hasUsefulObjectContent(args)) return [displayName];
|
|
146
|
+
return [displayName, formatJsonish(args, maxInputChars)];
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
function renderToolCallLines(lines: string[], theme?: RenderTheme) {
|
|
150
|
+
const activeTheme = theme ?? plainTheme;
|
|
151
|
+
const [title = "mcp", ...rest] = lines;
|
|
152
|
+
const styledTitle = activeTheme.fg("toolTitle", activeTheme.bold(title));
|
|
153
|
+
const styledRest = rest.map(line => activeTheme.fg("muted", line));
|
|
154
|
+
return new Text([styledTitle, ...styledRest].join("\n"), 0, 0);
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
export function renderMcpProxyToolCall(args: McpProxyToolCallInput, theme?: RenderTheme) {
|
|
158
|
+
return renderToolCallLines(formatMcpProxyToolCallLines(args), theme);
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
export function createMcpDirectToolCallRenderer(displayName: string) {
|
|
162
|
+
return (args: Record<string, unknown>, theme?: RenderTheme) => {
|
|
163
|
+
return renderToolCallLines(formatMcpDirectToolCallLines(displayName, args), theme);
|
|
164
|
+
};
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
function blockToLines(block: McpToolContentBlock): string[] {
|
|
168
|
+
if (block.type === "text") {
|
|
169
|
+
return block.text.split("\n");
|
|
170
|
+
}
|
|
171
|
+
return [`[image: ${block.mimeType}]`];
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
function collectCollapsedResultLines(
|
|
175
|
+
content: AgentToolResult<McpToolResultDetails>["content"],
|
|
176
|
+
maxLines: number,
|
|
177
|
+
maxChars: number,
|
|
178
|
+
): McpToolResultDisplay {
|
|
179
|
+
if (content.length === 0) return { lines: ["(empty result)"], truncated: false };
|
|
180
|
+
|
|
181
|
+
const lines: string[] = [];
|
|
182
|
+
let remainingChars = maxChars;
|
|
183
|
+
let truncated = false;
|
|
184
|
+
|
|
185
|
+
const appendLine = (line: string) => {
|
|
186
|
+
if (lines.length >= maxLines || remainingChars <= 0) {
|
|
187
|
+
truncated = true;
|
|
188
|
+
return false;
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
if (line.length > remainingChars) {
|
|
192
|
+
lines.push(line.slice(0, remainingChars));
|
|
193
|
+
truncated = true;
|
|
194
|
+
remainingChars = 0;
|
|
195
|
+
return false;
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
lines.push(line);
|
|
199
|
+
remainingChars -= line.length + 1;
|
|
200
|
+
return true;
|
|
201
|
+
};
|
|
202
|
+
|
|
203
|
+
for (const block of content) {
|
|
204
|
+
if (block.type !== "text") {
|
|
205
|
+
if (!appendLine(`[image: ${block.mimeType}]`)) break;
|
|
206
|
+
continue;
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
let start = 0;
|
|
210
|
+
while (start <= block.text.length) {
|
|
211
|
+
const newline = block.text.indexOf("\n", start);
|
|
212
|
+
const line = newline === -1 ? block.text.slice(start) : block.text.slice(start, newline);
|
|
213
|
+
if (!appendLine(line)) break;
|
|
214
|
+
if (newline === -1) break;
|
|
215
|
+
start = newline + 1;
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
if (truncated) break;
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
if (lines.length === 0) lines.push("");
|
|
222
|
+
if (truncated && lines.length >= maxLines) lines.push("…");
|
|
223
|
+
return { lines, truncated };
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
export function formatMcpToolResultIdentity(details: McpToolResultDetails | undefined): string | null {
|
|
227
|
+
if (details?.mode !== "call") return null;
|
|
228
|
+
const server = typeof details.server === "string"
|
|
229
|
+
? details.server
|
|
230
|
+
: typeof details.hintServer === "string"
|
|
231
|
+
? details.hintServer
|
|
232
|
+
: null;
|
|
233
|
+
if (!server) return null;
|
|
234
|
+
if (typeof details.tool === "string") return `MCP ${server}/${details.tool}`;
|
|
235
|
+
if (typeof details.resourceUri === "string") return `MCP ${server} resource ${details.resourceUri}`;
|
|
236
|
+
if (typeof details.requestedTool === "string") return `MCP ${server}/${details.requestedTool}`;
|
|
237
|
+
return null;
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
export function formatMcpToolResultLines(
|
|
241
|
+
result: Pick<AgentToolResult<McpToolResultDetails>, "content">,
|
|
242
|
+
expanded: boolean,
|
|
243
|
+
maxCollapsedLines = 3,
|
|
244
|
+
maxCollapsedChars = DEFAULT_MAX_COLLAPSED_CHARS,
|
|
245
|
+
): McpToolResultDisplay {
|
|
246
|
+
if (!expanded) {
|
|
247
|
+
return collectCollapsedResultLines(result.content, maxCollapsedLines, maxCollapsedChars);
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
const allLines = result.content.flatMap(blockToLines);
|
|
251
|
+
const lines = allLines.length > 0 ? allLines : ["(empty result)"];
|
|
252
|
+
return { lines, truncated: false };
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
export function renderMcpToolResult(
|
|
256
|
+
result: AgentToolResult<unknown>,
|
|
257
|
+
options: ToolRenderResultOptions,
|
|
258
|
+
theme?: RenderTheme,
|
|
259
|
+
context?: McpToolRenderContext,
|
|
260
|
+
) {
|
|
261
|
+
const activeTheme = theme ?? plainTheme;
|
|
262
|
+
if (options.isPartial) {
|
|
263
|
+
return new Text(activeTheme.fg("warning", "Running MCP tool..."), 0, 0);
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
const details = typeof result.details === "object" && result.details !== null
|
|
267
|
+
? result.details as McpToolResultDetails
|
|
268
|
+
: {};
|
|
269
|
+
const hasErrorDetails = Boolean(details.error);
|
|
270
|
+
const expanded = options.expanded || context?.isError === true || hasErrorDetails;
|
|
271
|
+
const display = formatMcpToolResultLines(result, expanded);
|
|
272
|
+
const identity = formatMcpToolResultIdentity(details);
|
|
273
|
+
const output = [
|
|
274
|
+
...(identity ? [activeTheme.fg("muted", identity)] : []),
|
|
275
|
+
...display.lines.map((line) => activeTheme.fg("toolOutput", line)),
|
|
276
|
+
].join("\n");
|
|
277
|
+
|
|
278
|
+
return new CollapsibleText(
|
|
279
|
+
output,
|
|
280
|
+
expanded,
|
|
281
|
+
DEFAULT_MAX_COLLAPSED_LINES + (identity ? 1 : 0),
|
|
282
|
+
activeTheme.fg("muted", "…"),
|
|
283
|
+
activeTheme.fg("muted", `(${keyHint("app.tools.expand", "to expand")})`),
|
|
284
|
+
display.truncated,
|
|
285
|
+
);
|
|
286
|
+
}
|