import { existsSync, readFileSync } from "node:fs"; import { fileURLToPath } from "node:url"; import { QUERY_MCP_SERVER } from "../src/runtime/product-mcp-tools.js"; import { getInternalBridgeConfig } from "./internalBridge.js"; import type { McpServerConfig } from "../src/runtime/mcp-config.js"; import { DEFAULT_QUERY_REQUEST_TIMEOUT_MS, MAX_NATIVE_QUERY_TIMEOUT_MS } from "../src/mcp/query-timeouts.js"; // Register a native MCP connection, never plugin query tools or an HTTP query // executor. OpenCode supplies ai.opencode/sessionID in each tools/call _meta. export function queryMcpConnection(): McpServerConfig | null { const path = process.env.TJWATER_AGENT_MCP_CONNECTION_PATH ?? fileURLToPath(new URL("../data/mcp-query/connection.json", import.meta.url)); if (!existsSync(path)) return null; const data = JSON.parse(readFileSync(path, "utf8")) as { url: string; executionTimeoutMs?: number }; const url = new URL(data.url); if (url.protocol !== "http:" || url.hostname !== "127.0.0.1" || url.pathname !== "/mcp" || url.username || url.password || url.search || url.hash) throw new Error(`${QUERY_MCP_SERVER} requires the host-owned loopback endpoint`); const execution = data.executionTimeoutMs === undefined ? DEFAULT_QUERY_REQUEST_TIMEOUT_MS : data.executionTimeoutMs; if (!Number.isInteger(execution) || execution < DEFAULT_QUERY_REQUEST_TIMEOUT_MS || execution > MAX_NATIVE_QUERY_TIMEOUT_MS) throw new Error(`${QUERY_MCP_SERVER} has an invalid execution timeout`); return { type: "remote", url: url.href, protocol: "2026-07-28", oauth: false, codemode: false, headers: { "x-agent-internal-token": getInternalBridgeConfig().internalToken }, timeout: { execution } }; }