From e09e0a4e2c711ef1bb5e122ff9a151976e0f5db0 Mon Sep 17 00:00:00 2001 From: Serhii Rudenko Date: Thu, 3 Dec 2026 08:11:58 +0200 Subject: [PATCH] Support function calling in the local API through MCP Agents such as SolidCraft send `tools` and got a 400, because the subscription CLIs answer with text only. The CLIs do support MCP, so a request with tools now starts the CLI with one MCP server, served by the API at /mcp/, that offers exactly the caller's functions. A model's call is returned as OpenAI `tool_calls` while the CLI waits on its MCP call; the caller's next request with `role: "tool"` results answers it and the same process carries on. The model uses its native tool calling, and later steps take a second or two instead of a new process with the whole conversation. Claude Code gets --mcp-config with --allowedTools mcp__client (its own tools stay off); Codex gets the server as its only MCP server with default_tools_approval_mode="approve", since codex exec never asks. Idle sessions stop after 10 minutes, at most 8 wait at once, and a request whose results match no session starts over from the written-out conversation. Gemini CLI is not wired up yet and answers tools with 400. --- README.md | 2 +- docs-dev/architecture.md | 13 ++ docs/api.md | 17 ++- src/main/subscriptions/api.ts | 8 +- src/main/subscriptions/bridge.test.ts | 136 ++++++++++++++++++ src/main/subscriptions/bridge.ts | 195 ++++++++++++++++++++++++++ src/main/subscriptions/cli.test.ts | 23 +++ src/main/subscriptions/cli.ts | 47 +++++-- src/main/subscriptions/openapi.ts | 58 +++++++- src/main/subscriptions/server.test.ts | 7 +- src/main/subscriptions/server.ts | 88 ++++++++++-- 11 files changed, 561 insertions(+), 33 deletions(-) create mode 100644 src/main/subscriptions/bridge.test.ts create mode 100644 src/main/subscriptions/bridge.ts diff --git a/README.md b/README.md index b62f23a..284e0ed 100644 --- a/README.md +++ b/README.md @@ -96,7 +96,7 @@ Developer documentation (`docs-dev/`, not published): ## Status -Done: Claude Code and Codex clients, a local OpenAI-compatible API that answers with Claude, ChatGPT and Gemini subscriptions through their CLIs, Overview drawn as the live request path with its fallbacks, step-by-step "Check now", mitmproxy service with headroom fallback, headroom service with its options in Settings, +Done: Claude Code and Codex clients, a local OpenAI-compatible API that answers with Claude, ChatGPT and Gemini subscriptions through their CLIs (with function calling for Claude and Codex), Overview drawn as the live request path with its fallbacks, step-by-step "Check now", mitmproxy service with headroom fallback, headroom service with its options in Settings, statistics with expandable recent requests, approved tool installation/update checks and RTK client connections, settings, start at login. Illustrated documentation builds into GitHub Pages on release. GitHub CI validates every push; version tags publish deb/rpm releases. Not yet: package installation smoke tests, Cursor client, macOS. Planned headroom improvements: diagnostics, quotas, detailed savings, CCR inspection and tuning; see [the roadmap](docs-dev/roadmap.md). diff --git a/docs-dev/architecture.md b/docs-dev/architecture.md index 44e84af..ab1260d 100644 --- a/docs-dev/architecture.md +++ b/docs-dev/architecture.md @@ -84,6 +84,7 @@ port>/v1`. Codex talks plain HTTP and WebSocket to it, so no certificate is invo | `subscriptions/cli.ts` | Headless runs of Claude Code (`-p`, stream-json), Codex CLI (`exec --json`) and Gemini CLI (`--output-format json`): argument building, transcript of a chat, output parsing, error kinds (login, limit, missing, timeout), API keys stripped from the environment | | `subscriptions/logins.ts` | `Subscriptions`: per tool installed/version/login state and models (`codex debug models`), and the app's own logins in `/subscriptions/` (link + pasted code; Gemini in a pseudo-terminal through Python's `pty`) | | `subscriptions/server.ts` | `ApiServer`: OpenAI-compatible `/v1/models` and `/v1/chat/completions` (JSON and SSE) on 127.0.0.1 with a bearer key, at most four tool processes at once; `/docs` and `/openapi.json` without the key (live models in the spec only with it); every request must carry a `Host` of 127.0.0.1, localhost or [::1] on our port, against DNS rebinding | +| `subscriptions/bridge.ts` | `ToolBridge`: function calling (`tools`) through an MCP server per tool process at `/mcp/`; holds the model's calls until the caller sends their results, stops idle sessions | | `subscriptions/openapi.ts` | OpenAPI 3.1 description (current models as `model` examples) and the Swagger UI page, which loads swagger-ui-dist from jsDelivr pinned with SRI hashes | | `subscriptions/api.ts` | `SubscriptionApi`: settings (`api` in `state.json`), start/stop, key, cached subscription checks for the API tab | | `status.ts` | `StatusMonitor` (polling, combined health; `refresh(onStep)` reports each component for a manual check) and the status-line functions for each card | @@ -150,6 +151,18 @@ Gemini CLI get `HTTPS_PROXY`, `NODE_EXTRA_CA_CERTS` and `NO_PROXY` in their envi sending credentials to a foreign listener) and, for the HTTPS proxy, the CA file exists; otherwise the request goes direct. The API never starts or waits for the proxy. +Function calling goes through the tools' MCP support (`bridge.ts`). A request with `tools` starts the CLI with one MCP +server, `client`, served by the API itself at `/mcp/` (streamable HTTP, JSON responses; the random token in +the path is the only credential, as the CLI cannot send the API key). Claude Code gets it through `--mcp-config` with +`--allowedTools mcp__client` (its built-in tools stay off with `--tools ""`); Codex through +`-c mcp_servers={client={url=…,default_tools_approval_mode="approve"}}`, since `codex exec` never asks. A `tools/call` +is held open (server-sent event response, headers sent at once) and returned to the HTTP caller as `tool_calls`, after +150 ms for more calls of the same step. The caller's next request with `role: "tool"` results whose ids belong to a +waiting session answers those MCP calls, and the same process continues; any other request starts a new session from +the written-out conversation. A session idle for 10 minutes, a cancelled request or API shutdown kills the process; +at most 8 sessions wait at once (the oldest idle one goes). The process may run for up to 2 hours. Gemini CLI is not +wired up yet: requests with `tools` for it get 400. + "Your own login" leaves `CLAUDE_CONFIG_DIR`/`CODEX_HOME`/`GEMINI_CLI_HOME` alone; "the app's login" points them at `/subscriptions/`. The app never logs the user's own tool login in or out, and writes Gemini's `security.auth.selectedType` only in its own folder. Installing a missing CLI runs `npm install --global --prefix diff --git a/docs/api.md b/docs/api.md index e9c9f88..58d9253 100644 --- a/docs/api.md +++ b/docs/api.md @@ -85,7 +85,7 @@ print(reply.choices[0].message.content) | Endpoint | What | |---|---| | `GET /v1/models` | Models of the installed, logged-in subscriptions | -| `POST /v1/chat/completions` | An answer, at once or streamed (`"stream": true`) | +| `POST /v1/chat/completions` | An answer, at once or streamed (`"stream": true`), with function calling for Claude and Codex | | `GET /docs` | Swagger UI: browse the API and try requests from the browser | | `GET /openapi.json` | The OpenAPI 3.1 description, for code generators and API clients | @@ -105,7 +105,20 @@ integrity-checked), so it needs internet access; `openapi.json` does not. account; `gemini/auto`, `gemini/pro`, `gemini/flash`, `gemini/flash-lite`. Just `claude`, `codex` or `gemini` uses the tool's default (for Codex, the first model it lists). -**Limits.** Text only: tool (function) calls, images and audio are refused with an error. `temperature`, +### Function calling + +Programs that act through functions (agents, CAD and editor plugins, anything that sends `tools`) work with `claude/…` +and `codex/…` models, the same way as with the OpenAI API: the answer ends with `finish_reason: "tool_calls"`, the +program runs the functions and sends the conversation again with one `role: "tool"` message per call. + +Behind it, the tool gets the program's functions as its only MCP server, which the app serves itself, so the model calls +them the way it was trained to. The tool process waits while the program runs a function and carries on with the +result, so each next step takes a second or two instead of a new start. If the program does not send the results +within 10 minutes, the app stops that process; a later request then starts a new one from the whole conversation. +Functions run in the program that sent them, never on this computer by the tool. Gemini models answer requests with +`tools` with an error for now. + +**Limits.** Text only: images and audio are refused with an error. `temperature`, `max_tokens` and similar options are accepted but ignored, because the tools do not take them. Claude Code streams its answer as it writes; Codex and Gemini CLI send it in one piece at the end. Token counts come from the tools (Gemini CLI reports none). diff --git a/src/main/subscriptions/api.ts b/src/main/subscriptions/api.ts index db2e839..44619cf 100644 --- a/src/main/subscriptions/api.ts +++ b/src/main/subscriptions/api.ts @@ -8,6 +8,8 @@ import { ApiServer, newKey } from './server' /** How long a subscription check (versions, logins, Codex's models) stays fresh. */ const INFO_TTL_MS = 60_000 +/** Longest agent loop (a request with functions and its follow-ups) one tool process may run. */ +const SESSION_TIMEOUT_MS = 2 * 60 * 60_000 /** Checks the API settings from the API tab; returns an error message or null. */ export function validateApiSettings(s: ApiSettings, taken: { port: number; what: string }[]): string | null { @@ -44,14 +46,16 @@ export class SubscriptionApi extends EventEmitter { version: deps.version, models: async () => (await this.subscriptionInfos()).flatMap((s) => s.program && s.loggedIn !== false ? [{ id: s.id, owner: s.id }, ...s.models.map((m) => ({ id: m.id, owner: s.id }))] : []), - answer: async (id, model, messages, onDelta, signal) => { + answer: async (id, model, messages, onDelta, signal, mcpUrl) => { const program = await this.deps.subscriptions.program(id) if (!program) throw new Error(`${id} is not installed`) const source = this.deps.prefs().sources[id] return ask(id, { program, model: model || (await this.defaultModel(id)), messages, onDelta, signal, env: await this.deps.subscriptions.environment(id, source), - proxy: (await this.deps.route?.(id)) ?? null + proxy: (await this.deps.route?.(id)) ?? null, + // With the caller's functions the process lives for the whole agent loop; the bridge stops it when idle. + ...(mcpUrl ? { mcpUrl, timeoutMs: SESSION_TIMEOUT_MS } : {}) }) } }) diff --git a/src/main/subscriptions/bridge.test.ts b/src/main/subscriptions/bridge.test.ts new file mode 100644 index 0000000..ec5bd4f --- /dev/null +++ b/src/main/subscriptions/bridge.test.ts @@ -0,0 +1,136 @@ +import { afterEach, describe, expect, it } from 'vitest' +import { ToolBridge } from './bridge' +import type { Answer } from './cli' +import { ApiServer, type AnswerFn } from './server' + +const KEY = 'adp-test-key' +let server: ApiServer | null = null + +afterEach(async () => { + await server?.stop() + server = null +}) + +/** A tool's MCP client: one JSON-RPC request to the bridge, its result (read from JSON or a server-sent event). */ +async function rpc(url: string, method: string, params: object = {}): Promise> { + const res = await fetch(url, { + method: 'POST', + headers: { 'content-type': 'application/json', accept: 'application/json, text/event-stream' }, + body: JSON.stringify({ jsonrpc: '2.0', id: 1, method, params }) + }) + const text = await res.text() + const json = text.startsWith('event:') ? text.split('\n').find((l) => l.startsWith('data: '))!.slice(6) : text + return (JSON.parse(json) as { result: Record }).result +} + +const done = (text: string): Answer => ({ text, usage: { inputTokens: 3, outputTokens: 2 }, finish: 'stop' }) + +async function start(answer: AnswerFn): Promise { + server = new ApiServer({ key: () => KEY, answer, models: async () => [] }) + await server.start(0) + return `http://127.0.0.1:${server.port}/v1/chat/completions` +} + +const post = (url: string, body: object): Promise => + fetch(url, { method: 'POST', headers: { authorization: `Bearer ${KEY}`, 'content-type': 'application/json' }, body: JSON.stringify(body) }) + +const weather = { type: 'function', function: { name: 'get_weather', description: 'Weather in a city', parameters: { type: 'object', properties: { city: { type: 'string' } } } } } +const ask = { role: 'user', content: 'Weather in Kyiv?' } + +/** A tool that lists the functions, calls get_weather and answers with its result. */ +const agent: AnswerFn = async (_id, _model, _messages, _onDelta, _signal, mcpUrl) => { + if (!mcpUrl) return done('no functions') + await rpc(mcpUrl, 'initialize', { protocolVersion: '2025-06-18' }) + const { tools } = await rpc(mcpUrl, 'tools/list') as { tools: { name: string; inputSchema: object }[] } + const result = await rpc(mcpUrl, 'tools/call', { name: tools[0].name, arguments: { city: 'Kyiv' } }) as { content: { text: string }[] } + return done(`Weather: ${result.content[0].text}`) +} + +describe('function calling through the bridge', () => { + it('returns the model\'s call to the caller and carries on with its result', async () => { + const url = await start(agent) + const first = await (await post(url, { model: 'codex', tools: [weather], messages: [ask] })).json() as { + choices: { message: { content: string | null; tool_calls: { id: string; type: string; function: { name: string; arguments: string } }[] }; finish_reason: string }[] + } + expect(first.choices[0].finish_reason).toBe('tool_calls') + const call = first.choices[0].message.tool_calls[0] + expect(call).toMatchObject({ type: 'function', function: { name: 'get_weather', arguments: '{"city":"Kyiv"}' } }) + expect(server!.bridge.size).toBe(1) + + const second = await (await post(url, { + model: 'codex', tools: [weather], + messages: [ask, { role: 'assistant', content: null, tool_calls: [call] }, { role: 'tool', tool_call_id: call.id, content: 'sunny' }] + })).json() as { choices: { message: { content: string }; finish_reason: string }[] } + expect(second.choices[0]).toMatchObject({ message: { content: 'Weather: sunny' }, finish_reason: 'stop' }) + expect(server!.bridge.size).toBe(0) + }) + + it('streams the call as a tool_calls chunk', async () => { + const url = await start(agent) + const text = await (await post(url, { model: 'claude', stream: true, tools: [weather], messages: [ask] })).text() + const chunks = text.split('\n\n').filter((e) => e.startsWith('data: {')).map((e) => JSON.parse(e.slice(6)) as { choices: { delta: { tool_calls?: { function: { name: string } }[] }; finish_reason: string | null }[] }) + expect(chunks.some((c) => c.choices[0].delta.tool_calls?.[0].function.name === 'get_weather')).toBe(true) + expect(chunks.at(-1)!.choices[0].finish_reason).toBe('tool_calls') + expect(text.trim().endsWith('data: [DONE]')).toBe(true) + }) + + it('starts over from the written-out conversation when no session waits for the results', async () => { + const seen: string[] = [] + const url = await start(async (_id, _model, messages) => { + seen.push(...messages.map((m) => m.role)) + return done('ok') + }) + const res = await post(url, { + model: 'claude', tools: [weather], + messages: [ask, { role: 'assistant', content: null, tool_calls: [{ id: 'call_old', type: 'function', function: { name: 'get_weather', arguments: '{}' } }] }, + { role: 'tool', tool_call_id: 'call_old', content: 'rain' }] + }) + expect(res.status).toBe(200) + expect(seen).toEqual(['user', 'assistant', 'tool']) + }) + + it('refuses functions for Gemini and malformed tools', async () => { + const url = await start(agent) + expect((await post(url, { model: 'gemini', tools: [weather], messages: [ask] })).status).toBe(400) + expect((await post(url, { model: 'claude', tools: [{ type: 'function', function: { name: 'bad name' } }], messages: [ask] })).status).toBe(400) + // tool_choice "none" offers no functions: a plain answer. + const plain = await (await post(url, { model: 'gemini', tools: [weather], tool_choice: 'none', messages: [ask] })).json() as { choices: { message: { content: string } }[] } + expect(plain.choices[0].message.content).toBe('no functions') + }) + + it('refuses MCP requests for sessions that do not exist', async () => { + await start(agent) + expect((await fetch(`http://127.0.0.1:${server!.port}/mcp/nope`, { method: 'POST', body: '{}' })).status).toBe(404) + }) +}) + +describe('ToolBridge', () => { + it('stops a session whose caller does not bring the results back', async () => { + let signal: AbortSignal | null = null + server = new ApiServer({ + key: () => KEY, models: async () => [], bridgeIdleMs: 100, + answer: async (...args) => { signal = args[4]; return agent(...args) } + }) + await server.start(0) + const res = await post(`http://127.0.0.1:${server.port}/v1/chat/completions`, { model: 'codex', tools: [weather], messages: [ask] }) + expect(((await res.json()) as { choices: { finish_reason: string }[] }).choices[0].finish_reason).toBe('tool_calls') + expect(server.bridge.size).toBe(1) + await new Promise((resolve) => setTimeout(resolve, 300)) + expect(server.bridge.size).toBe(0) + expect(signal!.aborted).toBe(true) + }) + + it('stops every session on stopAll', async () => { + const bridge = new ToolBridge(() => '') + let signal: AbortSignal | null = null + const step = bridge.start([{ name: 'f', description: '', parameters: { type: 'object' } }], (_url, _delta, s) => { + signal = s + return new Promise(() => {}) + }, () => {}, new AbortController().signal) + expect(bridge.size).toBe(1) + bridge.stopAll() + expect(signal!.aborted).toBe(true) + expect(bridge.size).toBe(0) + await expect(step).rejects.toThrow('stopped') + }) +}) diff --git a/src/main/subscriptions/bridge.ts b/src/main/subscriptions/bridge.ts new file mode 100644 index 0000000..1a65189 --- /dev/null +++ b/src/main/subscriptions/bridge.ts @@ -0,0 +1,195 @@ +import { randomBytes } from 'node:crypto' +import type { IncomingMessage, ServerResponse } from 'node:http' +import type { Answer } from './cli' + +/** + * Function calling for API callers, through the tools' own MCP support. A request with `tools` starts the + * subscription's CLI with one MCP server, served here at /mcp/, that offers exactly the caller's + * functions. When the model calls one, the HTTP request is answered with `tool_calls` while the CLI keeps + * waiting on its MCP call; the caller's next request brings `role: "tool"` results with the same ids, which + * answer the waiting MCP calls, and the model carries on. The CLI stays one process for the whole agent loop. + */ + +export interface ClientTool { name: string; description: string; parameters: Record } +export interface ToolCall { id: string; name: string; arguments: string } +export interface ToolResult { id: string; content: string } + +/** Runs the tool with the MCP server at `mcpUrl`; resolves with its final answer. */ +export type RunFn = (mcpUrl: string, onDelta: (text: string) => void, signal: AbortSignal) => Promise + +/** After a call, wait this long for more calls of the same step, so parallel calls go back together. */ +const GATHER_MS = 150 +/** A session whose caller does not bring the results back within this time is stopped. */ +export const IDLE_MS = 10 * 60_000 +/** Sessions waiting for their callers at once; the oldest goes when a new one would pass this. */ +const MAX_SESSIONS = 8 +const MAX_MCP_BODY = 1024 * 1024 + +interface Call { call: ToolCall; reply: (content: string | null) => void } + +class Session { + readonly token = randomBytes(18).toString('base64url') + readonly controller = new AbortController() + /** Sent to the caller, waiting for its results. */ + readonly sent = new Map() + /** Made by the model, not yet sent to the caller. */ + fresh: Call[] = [] + outcome: { answer: Answer } | { error: unknown } | null = null + onDelta: (text: string) => void = () => {} + text = '' + idle: NodeJS.Timeout | null = null + stopped = false + wake: () => void = () => {} + + constructor(readonly tools: ClientTool[]) {} +} + +export class ToolBridge { + private readonly sessions = new Map() + + /** `base` is the API's own address, e.g. http://127.0.0.1:8879. */ + constructor(private readonly base: () => string, private readonly idleMs = IDLE_MS) {} + + get size(): number { + return this.sessions.size + } + + /** Starts a session for a new conversation; resolves at the first tool calls or the final answer. */ + async start(tools: ClientTool[], run: RunFn, onDelta: (text: string) => void, signal: AbortSignal): Promise { + if (this.sessions.size >= MAX_SESSIONS) { + const oldest = [...this.sessions.values()].find((s) => s.idle) + if (oldest) this.stop(oldest) + } + const session = new Session(tools) + this.sessions.set(session.token, session) + run(`${this.base()}/mcp/${session.token}`, (text) => { session.text += text; session.onDelta(text) }, session.controller.signal) + .then((answer) => { session.outcome = { answer } }, (error: unknown) => { session.outcome = { error } }) + .finally(() => session.wake()) + return this.next(session, onDelta, signal) + } + + /** + * Continues the session waiting for these results; null when none is (a new conversation, or one whose + * session ended), so the caller starts a new session from the whole conversation. + */ + async resume(results: ToolResult[], onDelta: (text: string) => void, signal: AbortSignal): Promise { + const session = [...this.sessions.values()].find((s) => results.some((r) => s.sent.has(r.id))) + if (!session) return null + for (const r of results) { + session.sent.get(r.id)?.reply(r.content) + session.sent.delete(r.id) + } + return this.next(session, onDelta, signal) + } + + /** Waits for the session's next step: tool calls for the caller, or the end of the run. */ + private async next(session: Session, onDelta: (text: string) => void, signal: AbortSignal): Promise { + if (session.idle) clearTimeout(session.idle) + session.idle = null + session.onDelta = onDelta + session.text = '' + const abort = (): void => this.stop(session) + signal.addEventListener('abort', abort) + try { + for (;;) { + if (session.outcome) { + this.stop(session) + if ('error' in session.outcome) throw session.outcome.error + const { answer } = session.outcome + return { ...answer, text: session.text || answer.text } + } + if (session.fresh.length) { + await new Promise((resolve) => setTimeout(resolve, GATHER_MS)) + if (session.outcome) continue + const calls = session.fresh + session.fresh = [] + for (const c of calls) session.sent.set(c.call.id, c) + session.idle = setTimeout(() => this.stop(session), this.idleMs) + return { text: session.text, usage: { inputTokens: 0, outputTokens: 0 }, finish: 'tool_calls', toolCalls: calls.map((c) => c.call) } + } + if (signal.aborted) throw new Error('the request was cancelled') + if (session.stopped) throw new Error('the function-calling session was stopped') + await new Promise((resolve) => { session.wake = resolve }) + } + } finally { + signal.removeEventListener('abort', abort) + session.onDelta = () => {} + } + } + + private stop(session: Session): void { + if (!this.sessions.delete(session.token)) return + session.stopped = true + if (session.idle) clearTimeout(session.idle) + session.controller.abort() + for (const c of [...session.fresh, ...session.sent.values()]) c.reply(null) + session.fresh = [] + session.sent.clear() + session.wake() + } + + stopAll(): void { + for (const session of [...this.sessions.values()]) this.stop(session) + } + + /** The MCP endpoint of one session (streamable HTTP, JSON responses, no server-sent notifications). */ + async mcp(token: string, req: IncomingMessage, res: ServerResponse): Promise { + const session = this.sessions.get(token) + if (!session) return void res.writeHead(404).end() + if (req.method === 'DELETE') return void res.writeHead(200).end() + if (req.method !== 'POST') return void res.writeHead(405, { allow: 'POST' }).end() + let message: { id?: string | number; method?: string; params?: { protocolVersion?: string; name?: string; arguments?: unknown } } + try { + let body = '' + for await (const chunk of req) { + body += String(chunk) + if (body.length > MAX_MCP_BODY) throw new Error('too large') + } + message = JSON.parse(body) as typeof message + } catch { + return void res.writeHead(400).end() + } + if (message.id === undefined) return void res.writeHead(202).end() // a notification + const reply = (result: unknown): void => { + const body = JSON.stringify({ jsonrpc: '2.0', id: message.id, result }) + res.writeHead(200, { 'content-type': 'application/json', 'content-length': Buffer.byteLength(body) }).end(body) + } + switch (message.method) { + case 'initialize': + return reply({ + protocolVersion: message.params?.protocolVersion ?? '2025-06-18', + capabilities: { tools: {} }, + serverInfo: { name: 'client', version: '1.0.0' }, + instructions: 'The functions of the program that sent this request. Call them to act in that program.' + }) + case 'ping': + return reply({}) + case 'tools/list': + return reply({ tools: session.tools.map((t) => ({ name: t.name, description: t.description, inputSchema: t.parameters })) }) + case 'tools/call': + return this.call(session, message.params?.name, message.params?.arguments, message.id!, res) + default: { + const body = JSON.stringify({ jsonrpc: '2.0', id: message.id, error: { code: -32601, message: `Method not found: ${String(message.method)}` } }) + return void res.writeHead(200, { 'content-type': 'application/json' }).end(body) + } + } + } + + /** Holds a tool call until the caller sends its result; the answer goes back as one server-sent event. */ + private call(session: Session, name: unknown, args: unknown, rpcId: string | number, res: ServerResponse): void { + const event = (result: unknown): void => { + if (!res.writableEnded) res.end(`event: message\ndata: ${JSON.stringify({ jsonrpc: '2.0', id: rpcId, result })}\n\n`) + } + // Headers now: the caller may take minutes, and HTTP clients give up on a response that has not started. + res.writeHead(200, { 'content-type': 'text/event-stream', 'cache-control': 'no-cache' }) + if (!session.tools.some((t) => t.name === name)) return event({ content: [{ type: 'text', text: `Unknown function ${String(name)}` }], isError: true }) + const call: Call = { + call: { id: `call_${randomBytes(12).toString('base64url')}`, name: name as string, arguments: JSON.stringify(args ?? {}) }, + reply: (content) => event(content === null + ? { content: [{ type: 'text', text: 'The request was stopped before the function returned.' }], isError: true } + : { content: [{ type: 'text', text: content }] }) + } + session.fresh.push(call) + session.wake() + } +} diff --git a/src/main/subscriptions/cli.test.ts b/src/main/subscriptions/cli.test.ts index b60fb38..e7eedad 100644 --- a/src/main/subscriptions/cli.test.ts +++ b/src/main/subscriptions/cli.test.ts @@ -91,6 +91,29 @@ describe('toolEnvironment', () => { }) }) +describe('caller functions', () => { + it('gives Claude Code only the bridge\'s MCP server and allows its tools', () => { + const { args } = command('claude', '', '', 'x', null, 'http://127.0.0.1:8879/mcp/t') + expect(args).toContain('--strict-mcp-config') + expect(JSON.parse(args[args.indexOf('--mcp-config') + 1])).toEqual({ mcpServers: { client: { type: 'http', url: 'http://127.0.0.1:8879/mcp/t' } } }) + expect(args[args.indexOf('--allowedTools') + 1]).toBe('mcp__client') + expect(args[args.indexOf('--tools') + 1]).toBe('') + }) + it('gives Codex the bridge as its only MCP server, its calls approved', () => { + expect(command('codex', '', '', 'x', null, 'http://127.0.0.1:8879/mcp/t').args) + .toContain('mcp_servers={client={url="http://127.0.0.1:8879/mcp/t",tool_timeout_sec=3600,default_tools_approval_mode="approve"}}') + }) + it('writes earlier calls and results into the transcript', () => { + const { prompt } = transcript([ + { role: 'user', content: 'Weather?' }, + { role: 'assistant', content: '', toolCalls: [{ id: 'c1', name: 'get_weather', arguments: '{"city":"Kyiv"}' }] }, + { role: 'tool', content: 'sunny', toolCallId: 'c1' } + ]) + expect(prompt).toContain('Assistant: [called function get_weather with {"city":"Kyiv"}]') + expect(prompt).toContain('Function result: sunny') + }) +}) + describe('proxy route', () => { const proxy = buildProxyEnv(8877, '/ca.pem', 8878) it('points Codex at the proxy\'s Codex listener on its command line', () => { diff --git a/src/main/subscriptions/cli.ts b/src/main/subscriptions/cli.ts index 6e49586..0f5590e 100644 --- a/src/main/subscriptions/cli.ts +++ b/src/main/subscriptions/cli.ts @@ -4,6 +4,7 @@ import { tmpdir } from 'node:os' import { join } from 'node:path' import type { SubscriptionId } from '@shared/ipc' import type { ProxyEnv } from '../proxy-env' +import type { ToolCall } from './bridge' /** * Runs a subscription's own command-line tool headless (Claude Code, Codex CLI, Gemini CLI), one @@ -60,11 +61,18 @@ const LIMIT_WORDS = ['usage limit', 'rate limit', 'limit reached', 'quota', '429 const LOGIN_WORDS = ['log in', 'login', 'logged in', 'not authenticated', 'unauthorized', '401', 'auth method', 'failed to authenticate', 'oauth', 'invalid api key'] -export type ChatRole = 'system' | 'developer' | 'user' | 'assistant' -export interface ChatTurn { role: ChatRole; content: string } +export type ChatRole = 'system' | 'developer' | 'user' | 'assistant' | 'tool' +export interface ChatTurn { + role: ChatRole + content: string + /** Functions the assistant called in this turn (OpenAI `tool_calls`). */ + toolCalls?: ToolCall[] + /** For a `tool` turn: the call it answers. */ + toolCallId?: string +} export interface Usage { inputTokens: number; outputTokens: number } -export interface Answer { text: string; usage: Usage; finish: 'stop' | 'length' } +export interface Answer { text: string; usage: Usage; finish: 'stop' | 'length' | 'tool_calls'; toolCalls?: ToolCall[] } export class CliError extends Error { constructor(message: string, readonly kind: 'login' | 'limit' | 'missing' | 'timeout' | 'other' = 'other') { @@ -75,9 +83,13 @@ export class CliError extends Error { /** A conversation as one prompt, for tools that take a single one, and its system prompt. */ export function transcript(messages: ChatTurn[]): { system: string; prompt: string } { const system = messages.filter((m) => m.role === 'system' || m.role === 'developer').map((m) => m.content).join('\n\n') - const turns = messages.filter((m) => (m.role === 'user' || m.role === 'assistant') && m.content) - if (turns.length === 1) return { system, prompt: turns[0].content } - const lines = turns.map((m) => `${m.role === 'user' ? 'User' : 'Assistant'}: ${m.content}`) + // Earlier function calls and their results are written out too: a new tool process knows only this text. + const said = (m: ChatTurn): string => [m.content, ...(m.toolCalls ?? []).map((c) => `[called function ${c.name} with ${c.arguments}]`)] + .filter(Boolean).join('\n') + const turns = messages.filter((m) => m.role !== 'system' && m.role !== 'developer' && said(m)) + if (turns.length === 1 && turns[0].role === 'user') return { system, prompt: turns[0].content } + const label = { user: 'User', assistant: 'Assistant', tool: 'Function result' } as Record + const lines = turns.map((m) => `${label[m.role]}: ${said(m)}`) lines.push("Write the assistant's next answer only.") return { system, prompt: lines.join('\n\n') } } @@ -95,8 +107,20 @@ export const GEMINI_TOOLS = ['read_file', 'read_many_files', 'list_directory', ' */ export const CODEX_DISABLED = ['shell_tool', 'unified_exec', 'view_image', 'apps', 'plugins', 'browser_use', 'computer_use', 'in_app_browser'] +/** Name of the MCP server that offers the API caller's functions to the tool. */ +export const MCP_SERVER = 'client' +/** How long a tool waits for one function result from the caller (the bridge stops idle sessions sooner). */ +const MCP_CALL_TIMEOUT_S = 3600 + +/** Codex's MCP servers as a TOML inline table: none, or ours with its calls allowed without asking. */ +function codexMcp(url: string | null): string { + if (!url) return '{}' + return `{${MCP_SERVER}={url=${JSON.stringify(url)},tool_timeout_sec=${MCP_CALL_TIMEOUT_S},default_tools_approval_mode="approve"}}` +} + /** The tool's arguments (without the program) and what it reads from stdin. */ -export function command(id: SubscriptionId, model: string, system: string, prompt: string, proxy: ProxyEnv | null = null): { args: string[]; stdin: string } { +export function command(id: SubscriptionId, model: string, system: string, prompt: string, proxy: ProxyEnv | null = null, + mcpUrl: string | null = null): { args: string[]; stdin: string } { if (model && !MODEL_NAME.test(model)) throw new CliError(`${SUBSCRIPTIONS[id].name}: invalid model name ${JSON.stringify(model)}`) const pick = model ? [`--model=${model}`] : [] if (id === 'claude') { @@ -104,6 +128,8 @@ export function command(id: SubscriptionId, model: string, system: string, promp // so the answer comes from the subscription alone and carries no instructions of theirs. const args = ['-p', '--output-format', 'stream-json', '--verbose', '--include-partial-messages', '--tools', '', '--strict-mcp-config', '--no-session-persistence', '--setting-sources', 'project', ...pick] + // The caller's functions (see bridge.ts): our MCP server is the only one, and its tools are the only ones allowed. + if (mcpUrl) args.push('--mcp-config', JSON.stringify({ mcpServers: { [MCP_SERVER]: { type: 'http', url: mcpUrl } } }), '--allowedTools', `mcp__${MCP_SERVER}`) if (system) args.push('--system-prompt', system) return { args, stdin: prompt } } @@ -113,7 +139,7 @@ export function command(id: SubscriptionId, model: string, system: string, promp return { // --ignore-user-config: none of the user's MCP servers, plugins, profiles or base URL. args: ['exec', '--json', '--skip-git-repo-check', '--ephemeral', '--ignore-user-config', '--ignore-rules', '--sandbox', 'read-only', - ...CODEX_DISABLED.flatMap((f) => ['--disable', f]), '-c', 'mcp_servers={}', '-c', 'web_search="disabled"', + ...CODEX_DISABLED.flatMap((f) => ['--disable', f]), '-c', `mcp_servers=${codexMcp(mcpUrl)}`, '-c', 'web_search="disabled"', // Through our proxy's Codex listener, as the app's Codex setting does for the user's own runs. ...(proxy ? ['-c', `openai_base_url=${JSON.stringify(proxy.openaiBaseUrl)}`] : []), ...pick, '-'], stdin @@ -242,6 +268,8 @@ export interface AskOptions { env: NodeJS.ProcessEnv /** Our proxy, when it is up: the request goes through it. */ proxy?: ProxyEnv | null + /** The bridge's MCP server with the caller's functions (bridge.ts); Claude Code and Codex only. */ + mcpUrl?: string | null model: string messages: ChatTurn[] /** Called with each piece of text as it is written (Claude Code), or once with the whole answer. */ @@ -254,10 +282,11 @@ export interface AskOptions { export async function ask(id: SubscriptionId, o: AskOptions): Promise { const name = SUBSCRIPTIONS[id].name const { system, prompt } = transcript(o.messages) - const { args, stdin } = command(id, o.model, system, prompt, o.proxy ?? null) + const { args, stdin } = command(id, o.model, system, prompt, o.proxy ?? null, o.mcpUrl ?? null) // An empty folder: the tool finds no project files or instructions of its own there. const cwd = await fs.mkdtemp(join(tmpdir(), 'ai-desktop-proxy-api-')) let env = proxyEnvironment(o.env, id, o.proxy ?? null) + if (o.mcpUrl && id === 'claude') env = { ...env, MCP_TOOL_TIMEOUT: String(MCP_CALL_TIMEOUT_S * 1000) } if (id === 'gemini') { // System settings override the user's and the workspace's: no built-in tools, MCP servers or extensions. const settings = join(cwd, 'gemini-system-settings.json') diff --git a/src/main/subscriptions/openapi.ts b/src/main/subscriptions/openapi.ts index b95c831..2221af1 100644 --- a/src/main/subscriptions/openapi.ts +++ b/src/main/subscriptions/openapi.ts @@ -19,8 +19,9 @@ export function openApiSpec(baseUrl: string, version: string, models: string[]): title: 'AI Desktop Proxy local API', version, description: 'OpenAI-compatible API on this computer. Each request is answered by a subscription\'s own command-line tool ' - + '(Claude Code, Codex CLI, Gemini CLI) with the account it is logged in with. Text only: tool calls and images are refused; ' - + 'sampling options such as `temperature` and `max_tokens` are accepted and ignored.', + + '(Claude Code, Codex CLI, Gemini CLI) with the account it is logged in with. Text only (images are refused). ' + + 'Function calling (`tools`) works with `claude` and `codex` models. ' + + 'Sampling options such as `temperature` and `max_tokens` are accepted and ignored.', license: { name: 'MIT', url: 'https://github.com/redacid/ai-desktop-proxy/blob/main/LICENSE' } }, externalDocs: { description: 'User guide', url: 'https://redacid.github.io/ai-desktop-proxy/api/' }, @@ -42,7 +43,11 @@ export function openApiSpec(baseUrl: string, version: string, models: string[]): operationId: 'createChatCompletion', summary: 'Answer a conversation', description: 'With `stream: true` the answer comes as server-sent events (`chat.completion.chunk` objects, then `data: [DONE]`). ' - + 'Claude Code streams as it writes; Codex CLI and Gemini CLI send the whole answer at the end.', + + 'Claude Code streams as it writes; Codex CLI and Gemini CLI send the whole answer at the end.\n\n' + + 'With `tools` (claude and codex models), a model that calls a function ends its answer with `finish_reason: "tool_calls"`. ' + + 'Run the functions and send the conversation again with the assistant message and one `role: "tool"` message per call ' + + '(its `tool_call_id`); the same tool process carries on. Results not sent within 10 minutes end the session, and the ' + + 'next request starts a new one from the whole conversation.', requestBody: { required: true, content: { @@ -96,7 +101,9 @@ export function openApiSpec(baseUrl: string, version: string, models: string[]): type: 'object', required: ['role'], properties: { - role: { type: 'string', enum: ['system', 'developer', 'user', 'assistant'] }, + role: { type: 'string', enum: ['system', 'developer', 'user', 'assistant', 'tool'] }, + tool_calls: { type: 'array', description: 'Assistant messages: the calls it made', items: { $ref: '#/components/schemas/ToolCall' } }, + tool_call_id: { type: 'string', description: 'Tool messages: the call this is the result of' }, content: { oneOf: [ { type: 'string' }, @@ -117,10 +124,40 @@ export function openApiSpec(baseUrl: string, version: string, models: string[]): }, messages: { type: 'array', minItems: 1, items: { $ref: '#/components/schemas/Message' } }, stream: { type: 'boolean', default: false }, - stream_options: { type: 'object', properties: { include_usage: { type: 'boolean' } } } + stream_options: { type: 'object', properties: { include_usage: { type: 'boolean' } } }, + tools: { + type: 'array', + description: 'Functions the model may call (claude and codex models only)', + items: { + type: 'object', + required: ['type', 'function'], + properties: { + type: { const: 'function' }, + function: { + type: 'object', + required: ['name'], + properties: { + name: { type: 'string', pattern: '^[A-Za-z0-9_-]{1,64}$' }, + description: { type: 'string' }, + parameters: { type: 'object', description: 'JSON Schema of the arguments' } + } + } + } + } + }, + tool_choice: { description: '`"none"` offers no functions; other values are accepted and ignored' } }, additionalProperties: true }, + ToolCall: { + type: 'object', + required: ['id', 'type', 'function'], + properties: { + id: { type: 'string' }, + type: { const: 'function' }, + function: { type: 'object', properties: { name: { type: 'string' }, arguments: { type: 'string', description: 'JSON' } } } + } + }, Usage: { type: 'object', properties: { prompt_tokens: { type: 'integer' }, completion_tokens: { type: 'integer' }, total_tokens: { type: 'integer' } } @@ -139,8 +176,15 @@ export function openApiSpec(baseUrl: string, version: string, models: string[]): type: 'object', properties: { index: { type: 'integer' }, - message: { type: 'object', properties: { role: { const: 'assistant' }, content: { type: 'string' } } }, - finish_reason: { type: 'string', enum: ['stop', 'length'] } + message: { + type: 'object', + properties: { + role: { const: 'assistant' }, + content: { type: ['string', 'null'] }, + tool_calls: { type: 'array', items: { $ref: '#/components/schemas/ToolCall' } } + } + }, + finish_reason: { type: 'string', enum: ['stop', 'length', 'tool_calls'] } } } }, diff --git a/src/main/subscriptions/server.test.ts b/src/main/subscriptions/server.test.ts index 64fd7e9..627d75a 100644 --- a/src/main/subscriptions/server.test.ts +++ b/src/main/subscriptions/server.test.ts @@ -1,6 +1,6 @@ import { afterEach, describe, expect, it } from 'vitest' import { CliError } from './cli' -import { ApiServer, hostAllowed, parseModel, readMessages, type AnswerFn } from './server' +import { ApiServer, hostAllowed, parseModel, readMessages, readTools, type AnswerFn } from './server' const KEY = 'adp-test-key' let server: ApiServer | null = null @@ -26,10 +26,11 @@ describe('parseModel and readMessages', () => { expect(parseModel('gpt-4o')).toBeNull() expect(parseModel('claude/--tools=Bash')).toBeNull() }) - it('accepts text parts and refuses tools and images', () => { + it('accepts text parts, refuses images and reads functions', () => { expect(readMessages({ messages: [{ role: 'user', content: [{ type: 'text', text: 'a' }, { type: 'text', text: 'b' }] }] })) .toEqual([{ role: 'user', content: 'ab' }]) - expect(readMessages({ messages: [{ role: 'user', content: 'a' }], tools: [{}] })).toMatch(/not supported/) + expect(readTools({ tools: [{}] })).toMatch(/type "function"/) + expect(readTools({ tools: [{ type: 'function', function: { name: 'f' } }] })).toEqual([{ name: 'f', description: '', parameters: { type: 'object', properties: {} } }]) expect(readMessages({ messages: [{ role: 'user', content: [{ type: 'image_url' }] }] })).toMatch(/only text/) expect(readMessages({ messages: [{ role: 'system', content: 'x' }] })).toMatch(/user message/) }) diff --git a/src/main/subscriptions/server.ts b/src/main/subscriptions/server.ts index 587b3e7..38d1ad3 100644 --- a/src/main/subscriptions/server.ts +++ b/src/main/subscriptions/server.ts @@ -3,6 +3,7 @@ import { EventEmitter } from 'node:events' import { createServer, type IncomingMessage, type Server, type ServerResponse } from 'node:http' import type { SubscriptionId } from '@shared/ipc' import { CliError, MODEL_NAME, SUBSCRIPTION_IDS, type Answer, type ChatTurn } from './cli' +import { ToolBridge, type ClientTool, type ToolResult } from './bridge' import { openApiSpec, swaggerPage } from './openapi' /** @@ -16,8 +17,9 @@ const MAX_BODY = 4 * 1024 * 1024 /** One tool process per request; more wait their turn instead of starting dozens of them. */ const MAX_PARALLEL = 4 +/** Answers with the tool; `mcpUrl` is the bridge's MCP server with the caller's functions, for requests with `tools`. */ export type AnswerFn = (id: SubscriptionId, model: string, messages: ChatTurn[], onDelta: (text: string) => void, - signal: AbortSignal) => Promise + signal: AbortSignal, mcpUrl?: string) => Promise export interface ServerDeps { key: () => string @@ -26,6 +28,8 @@ export interface ServerDeps { models: () => Promise<{ id: string; owner: SubscriptionId }[]> /** App version, shown in the OpenAPI description. */ version?: string + /** How long a function-calling session waits for its caller (tests shorten it). */ + bridgeIdleMs?: number } export const newKey = (): string => `adp-${randomBytes(24).toString('base64url')}` @@ -45,17 +49,46 @@ interface ChatBody { stream?: unknown stream_options?: { include_usage?: boolean } tools?: unknown + tool_choice?: unknown +} + +/** Function names as OpenAI takes them; also valid MCP tool names. */ +const FUNCTION_NAME = /^[A-Za-z0-9_-]{1,64}$/ +/** Subscriptions whose tool can call the caller's functions (through the bridge). */ +export const FUNCTION_CALLING: SubscriptionId[] = ['claude', 'codex'] + +/** The functions the caller offers, or why they cannot be used. `tool_choice: "none"` offers none. */ +export function readTools(body: ChatBody): ClientTool[] | string { + if (body.tools === undefined || body.tools === null || body.tool_choice === 'none') return [] + if (!Array.isArray(body.tools)) return 'tools must be an array' + const tools: ClientTool[] = [] + for (const t of body.tools as { type?: unknown; function?: { name?: unknown; description?: unknown; parameters?: unknown } }[]) { + if (t?.type !== 'function' || !t.function) return 'only tools of type "function" are supported' + const { name, description, parameters } = t.function + if (typeof name !== 'string' || !FUNCTION_NAME.test(name)) return `invalid function name ${JSON.stringify(name)}` + if (tools.some((x) => x.name === name)) return `function ${name} is listed twice` + const schema = parameters && typeof parameters === 'object' && !Array.isArray(parameters) ? parameters as Record : {} + tools.push({ name, description: typeof description === 'string' ? description : '', parameters: { type: 'object', properties: {}, ...schema } }) + } + return tools +} + +/** The tool results the conversation ends with: what the caller brings back after `tool_calls`. */ +export function trailingResults(messages: ChatTurn[]): ToolResult[] { + const results: ToolResult[] = [] + for (let i = messages.length - 1; i >= 0 && messages[i].role === 'tool'; i--) { + results.unshift({ id: messages[i].toolCallId ?? '', content: messages[i].content }) + } + return results } /** The conversation of a chat completions request, or why it cannot be answered. */ export function readMessages(body: ChatBody): ChatTurn[] | string { if (!Array.isArray(body.messages) || !body.messages.length) return 'messages must be a non-empty array' - if (Array.isArray(body.tools) && body.tools.length) return 'tools (function calling) are not supported: the subscription tools answer with text only' const turns: ChatTurn[] = [] - for (const m of body.messages as { role?: unknown; content?: unknown }[]) { + for (const m of body.messages as { role?: unknown; content?: unknown; tool_calls?: unknown; tool_call_id?: unknown }[]) { const role = m?.role - if (role === 'tool' || role === 'function') return 'tool messages are not supported' - if (role !== 'system' && role !== 'developer' && role !== 'user' && role !== 'assistant') return `unknown role ${String(role)}` + if (role !== 'system' && role !== 'developer' && role !== 'user' && role !== 'assistant' && role !== 'tool') return `unknown role ${String(role)}` let content = '' if (typeof m.content === 'string') content = m.content else if (Array.isArray(m.content)) { @@ -63,7 +96,19 @@ export function readMessages(body: ChatBody): ChatTurn[] | string { if (parts.some((p) => p?.type !== 'text')) return 'only text content is supported' content = parts.map((p) => p.text ?? '').join('') } else if (m.content != null) return 'message content must be a string or an array of text parts' - turns.push({ role, content }) + const turn: ChatTurn = { role, content } + if (role === 'tool') { + if (typeof m.tool_call_id !== 'string') return 'a tool message needs tool_call_id' + turn.toolCallId = m.tool_call_id + } + if (role === 'assistant' && Array.isArray(m.tool_calls)) { + turn.toolCalls = (m.tool_calls as { id?: unknown; function?: { name?: unknown; arguments?: unknown } }[]).map((c) => ({ + id: String(c?.id ?? ''), + name: String(c?.function?.name ?? ''), + arguments: typeof c?.function?.arguments === 'string' ? c.function.arguments : JSON.stringify(c?.function?.arguments ?? {}) + })) + } + turns.push(turn) } if (!turns.some((t) => t.role === 'user' && t.content)) return 'messages need at least one user message with text' return turns @@ -113,6 +158,8 @@ async function readBody(req: IncomingMessage): Promise { export class ApiServer extends EventEmitter { private server: Server | null = null + /** Function calling through the tools' MCP support (bridge.ts). */ + readonly bridge: ToolBridge private waiting: (() => void)[] = [] active = 0 served = 0 @@ -120,6 +167,7 @@ export class ApiServer extends EventEmitter { constructor(private readonly deps: ServerDeps) { super() + this.bridge = new ToolBridge(() => `http://127.0.0.1:${this.port}`, deps.bridgeIdleMs) } /** The port actually listened on (useful with port 0). */ @@ -151,6 +199,7 @@ export class ApiServer extends EventEmitter { const server = this.server if (!server) return this.server = null + this.bridge.stopAll() server.closeAllConnections() await new Promise((resolve) => server.close(() => resolve())) this.emit('change') @@ -184,6 +233,8 @@ export class ApiServer extends EventEmitter { const models = authorized ? await this.deps.models().catch(() => []) : [] return sendJson(res, 200, openApiSpec(`http://127.0.0.1:${this.port}/v1`, this.deps.version ?? '0.0.0', models.map((m) => m.id))) } + // The bridge's MCP endpoint for one tool process; its unguessable path is the key. + if (path.startsWith('/mcp/')) return this.bridge.mcp(path.slice(5), req, res) if (!authorized) { return apiError(res, 401, 'Missing or wrong API key: send the key from the API tab as "Authorization: Bearer "', 'authentication_error', 'invalid_api_key') } @@ -211,6 +262,11 @@ export class ApiServer extends EventEmitter { if (!target) return apiError(res, 404, `Unknown model ${String(body.model)}: use one from GET /v1/models, e.g. claude/sonnet`, 'invalid_request_error', 'model_not_found') const messages = readMessages(body) if (typeof messages === 'string') return apiError(res, 400, messages) + const tools = readTools(body) + if (typeof tools === 'string') return apiError(res, 400, tools) + if (tools.length && !FUNCTION_CALLING.includes(target.id)) { + return apiError(res, 400, `tools (function calling) are not supported with ${target.id}: use claude or codex`, 'invalid_request_error', 'tools_not_supported') + } const id = `chatcmpl-${randomUUID()}` const created = Math.floor(Date.now() / 1000) @@ -226,7 +282,7 @@ export class ApiServer extends EventEmitter { this.emit('change') let started = false try { - const answer = await this.deps.answer(target.id, target.model, messages, (text) => { + const onDelta = (text: string): void => { if (!stream) return if (!started) { started = true @@ -234,7 +290,14 @@ export class ApiServer extends EventEmitter { res.write(chunk({ role: 'assistant', content: '' }, null)) } res.write(chunk({ content: text }, null)) - }, controller.signal) + } + // With functions: carry on the session waiting for these results, or start one for this conversation. + const answer = !tools.length + ? await this.deps.answer(target.id, target.model, messages, onDelta, controller.signal) + : (await this.bridge.resume(trailingResults(messages), onDelta, controller.signal)) + ?? await this.bridge.start(tools, (mcpUrl, delta, signal) => this.deps.answer(target.id, target.model, messages, delta, signal, mcpUrl), + onDelta, controller.signal) + const toolCalls = answer.toolCalls?.map((c, index) => ({ index, id: c.id, type: 'function', function: { name: c.name, arguments: c.arguments } })) const usage = { prompt_tokens: answer.usage.inputTokens, completion_tokens: answer.usage.outputTokens, total_tokens: answer.usage.inputTokens + answer.usage.outputTokens } this.served++ @@ -244,13 +307,20 @@ export class ApiServer extends EventEmitter { res.writeHead(200, { 'content-type': 'text/event-stream', 'cache-control': 'no-cache', connection: 'keep-alive' }) res.write(chunk({ role: 'assistant', content: '' }, null)) } + if (toolCalls) res.write(chunk({ tool_calls: toolCalls }, null)) res.write(chunk({}, answer.finish)) if (body.stream_options?.include_usage) res.write(`data: ${JSON.stringify({ id, object: 'chat.completion.chunk', created, model, choices: [], usage })}\n\n`) res.end('data: [DONE]\n\n') } else { sendJson(res, 200, { id, object: 'chat.completion', created, model, - choices: [{ index: 0, message: { role: 'assistant', content: answer.text }, finish_reason: answer.finish }], + choices: [{ + index: 0, + message: toolCalls + ? { role: 'assistant', content: answer.text || null, tool_calls: toolCalls.map(({ index: _, ...c }) => c) } + : { role: 'assistant', content: answer.text }, + finish_reason: answer.finish + }], usage }) }