@code-yeongyu/senpi
Version:
Coding agent CLI with read, bash, edit, write tools and session management
145 lines • 6.24 kB
JavaScript
import { Text } from "@earendil-works/pi-tui";
import { redactResolvedReferenceData, redactResolvedReferenceValues } from "../../../../config-reference-redaction.js";
import { forgetDispatchApproval } from "../../permission-system/dispatch.js";
import { registerDispatchIdentity } from "../../permission-system/dispatch-metadata.js";
import { ToolExecError } from "../errors.js";
import { applyMcpOutputGuard } from "../guard/output-guard.js";
import { callMcpTool } from "./call.js";
import { buildMcpToolNames, convertJsonSchemaToTypeBox, mapMcpToolResult, } from "./schema-compat.js";
/** Pair each catalog entry with its stable, collision-resolved mcp tool name.
* Shared by the full-tool builder and the Tier-B search catalog so names never
* drift between the two. */
export function mapMcpCatalogNames(entries, warn) {
const sorted = [...entries].sort(compareCatalogEntries);
const names = buildMcpToolNames(sorted.map((entry) => ({ serverName: entry.server, toolName: entry.tool })), warn);
return sorted.map((entry, index) => ({ entry, name: names[index] ?? "" }));
}
export function buildMcpToolDefinitions(entries, warn) {
return mapMcpCatalogNames(entries, warn).map(({ entry, name }) => createMcpToolDefinition(entry, name));
}
function createMcpToolDefinition(entry, name) {
const converted = convertJsonSchemaToTypeBox(entry.schema, entry.modern);
const label = `${entry.server}/${entry.tool}`;
registerDispatchIdentity(converted.schema, () => entry.invocation?.identity(entry));
return {
name,
label,
description: entry.description ?? `MCP tool ${label}`,
parameters: converted.schema,
executionMode: "parallel",
async execute(toolCallId, params, signal, onUpdate, context) {
const args = isRecord(params) ? params : {};
return await executeMcpCatalogEntry(entry, args, signal, onUpdate, {
toolCallId,
toolName: name,
input: args,
context,
});
},
renderCall(args, theme) {
return new Text(theme.fg("toolTitle", theme.bold(`${name} ${previewArgs(args)}`.trim())), 0, 0);
},
renderResult(result, options, theme) {
const title = options.isPartial
? `${name}: running`
: `${name}: ${result.details?.preview ?? "(empty result)"}`;
return new Text(theme.fg("toolOutput", title), 0, 0);
},
};
}
/** Full guarded call path for one catalog entry (lifecycle + retry + output
* guard). Shared by direct/search tool definitions and the Tier-C proxy. */
export async function executeMcpCatalogEntry(entry, args, signal, onUpdate, invocation) {
try {
const label = `${entry.server}/${entry.tool}`;
const outcome = await callMcpTool(entry, args, signal, onUpdate, label, invocation);
if (outcome.kind === "refused") {
const guarded = await applyMcpOutputGuard([{ type: "text", text: JSON.stringify({ error: outcome.error }) }], {
agentDir: entry.agentDir,
artifacts: entry.artifacts,
outputGuard: entry.outputGuard,
server: entry.server,
});
return {
content: toAgentContent(guarded),
details: redactResolvedReferenceData({
error: outcome.error,
preview: outcome.error.kind,
server: entry.server,
tool: entry.tool,
}),
};
}
const current = outcome.entry;
const mapped = mapMcpToolResult(normalizeCallToolResult(outcome.result));
if (!mapped.ok) {
throw new ToolExecError(redactResolvedReferenceValues(mapped.error.message), {
phase: "call",
serverName: entry.server,
});
}
const guarded = await applyMcpOutputGuard(mapped.content, {
agentDir: current.agentDir,
artifacts: current.artifacts,
outputGuard: current.outputGuard,
server: current.server,
});
const content = toAgentContent(guarded);
return {
content,
details: redactResolvedReferenceData({
preview: previewContent(content),
server: entry.server,
tool: entry.tool,
}),
};
}
finally {
if (invocation !== undefined)
forgetDispatchApproval(invocation.input);
}
}
function normalizeCallToolResult(result) {
if ("content" in result || "structuredContent" in result || "isError" in result) {
const candidate = result;
const normalized = {};
if (isMcpContentBlockArray(candidate.content))
normalized.content = candidate.content;
if (typeof candidate.isError === "boolean")
normalized.isError = candidate.isError;
if ("structuredContent" in candidate)
normalized.structuredContent = candidate.structuredContent;
return normalized;
}
return { structuredContent: result.toolResult };
}
function isMcpContentBlockArray(value) {
return Array.isArray(value);
}
function toAgentContent(blocks) {
return blocks.map((block) => {
if (block.type === "text" || block.type === "image")
return block;
return { type: "text", text: JSON.stringify(block) };
});
}
function previewContent(content) {
return truncatePreview(content
.map((block) => (block.type === "text" ? block.text : `[${block.mimeType} image]`))
.join(" ")
.trim() || "(empty result)");
}
function previewArgs(args) {
const text = JSON.stringify(args);
return text === undefined ? "" : truncatePreview(text);
}
function isRecord(value) {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
function truncatePreview(value) {
return value.length <= 120 ? value : `${value.slice(0, 117)}...`;
}
function compareCatalogEntries(left, right) {
return left.server.localeCompare(right.server) || left.tool.localeCompare(right.tool);
}
//# sourceMappingURL=register.js.map