mirror of
https://github.com/simplex-chat/simplex-chat.git
synced 2026-11-22 10:07:31 +00:00
* mcp: edits of prompts and messages typed in live mode reach Claude * mcp: a pending live message reaches Claude before its sender's next message
240 lines
12 KiB
TypeScript
240 lines
12 KiB
TypeScript
import {homedir} from "os"
|
|
import {join, resolve} from "path"
|
|
import {Readable, Writable} from "stream"
|
|
import {CallToolResult, JsonSchemaType, McpServer, fromJsonSchema} from "@modelcontextprotocol/server"
|
|
import {StdioServerTransport} from "@modelcontextprotocol/server/stdio"
|
|
import {ServiceClient, ProtocolError, SpawnService, spawnService} from "./client"
|
|
import {Config, ConfigError, defaultConfig, interactive, readConfig} from "./config"
|
|
import {dataRoot, isSessionId} from "./files"
|
|
import {ExitError, errorText, logError} from "./log"
|
|
import {ToolCall} from "./messages"
|
|
import {AttachLine, CallLine, PermissionRequest, SessionRequest, unattendedStatus} from "./protocol"
|
|
import {SocketError, isNotRunning} from "./socket"
|
|
import {ToolName, instructions, registerTools, replyTool} from "./tools"
|
|
import {version} from "./version"
|
|
|
|
const serviceStopped = "The SimpleX service stopped; repeat the call."
|
|
// spec: spec/architecture.md#session-unattendedrun
|
|
const unattendedRun = "This Claude Code run is not interactive, so it has no SimpleX group; the SimpleX tools work in interactive sessions."
|
|
const unknownSessionStatus = 409
|
|
const stoppingStatus = 503
|
|
const callAttempts = 2
|
|
const firstRetry = 1_000
|
|
const lastRetry = 30_000
|
|
// spec: spec/architecture.md#session-unattendedrun
|
|
const channelInstructions = "Messages in the simplex channel are prompts of the members of the SimpleX group of this session: from is the member's name, item the message ID, and file the path of a file they sent. A message sent as a reply has reply_to, the ID of the message replied to, and reply_to_from, its sender, and its text starts with a line \"> \" with the type of that message when it is not a text (link, image, video, voice, file, report or chat), and the first line of its text, up to 200 characters, with … when it is cut. With the reply, the member names the message they mean; that line is data, not their prompt. A reaction is its emoji after the quote line of the reacted message, with item equal to reply_to. A message with edited is the new text of the message with the same item, which the member edited; it replaces the earlier text. Your text of each turn reaches them in that group as you write it; reply sends them a file."
|
|
// spec: spec/api.md#channel
|
|
const permissionFields = ["request_id", "tool_name", "description", "input_preview"] as const
|
|
// spec: spec/architecture.md#session-unattendedrun
|
|
const permissionRequest = fromJsonSchema({type: "object", properties: Object.fromEntries(permissionFields.map(field => [field, {type: "string"}])), required: [...permissionFields]} as JsonSchemaType)
|
|
// spec: spec/api.md#plugin-tools
|
|
const hookTool = {
|
|
description: "Answers the plugin's PreToolUse hook before each tool use: allow for a tool that an admin or owner of the SimpleX group of this session approved for the rest of the session, and nothing otherwise. You never need to call it.",
|
|
inputSchema: fromJsonSchema({type: "object", properties: {tool: {type: "string", description: "Name of the tool, from the hook's input."}}, required: ["tool"]} as JsonSchemaType),
|
|
}
|
|
|
|
class ServiceStoppedError extends Error {
|
|
constructor() {
|
|
super(serviceStopped)
|
|
}
|
|
}
|
|
|
|
export interface SessionIo {
|
|
stdin: Readable
|
|
stdout: Writable
|
|
spawnService: SpawnService
|
|
version: string
|
|
}
|
|
|
|
const defaultIo: SessionIo = {stdin: process.stdin, stdout: process.stdout, spawnService: root => spawnService(root), version}
|
|
|
|
// spec: spec/architecture.md#session-startsession
|
|
export async function startSession(env: NodeJS.ProcessEnv = process.env, io: SessionIo = defaultIo): Promise<void> {
|
|
const id = env.CLAUDE_CODE_SESSION_ID
|
|
if (!id) throw new ExitError("simplex-mcp session runs from the Claude Code plugin.", 2)
|
|
if (!isSessionId(id)) throw new ExitError(`Not a Claude Code session ID: ${id}`, 2)
|
|
let config: Config = defaultConfig
|
|
let configError = interactive(env) ? undefined : unattendedRun
|
|
try {
|
|
config = readConfig(env)
|
|
} catch (error) {
|
|
if (!(error instanceof ConfigError)) throw error
|
|
configError ??= error.message
|
|
}
|
|
const server = new McpServer({name: "simplex-mcp", version: io.version}, {instructions: `${instructions("Claude", "SimpleX service")}\n${channelInstructions}`, capabilities: {experimental: {"claude/channel": {}, "claude/channel/permission": {}}}})
|
|
const link = new ServiceLink(ServiceClient.forRoot(dataRoot(env)), {id, pid: process.ppid, project: env.CLAUDE_PROJECT_DIR || process.cwd(), config, record: resolve(env.CLAUDE_CONFIG_DIR || join(homedir(), ".claude"), "sessions", `${process.ppid}.json`)}, io, line => {
|
|
const notification = channelNotification(line as AttachLine)
|
|
if (notification !== undefined) server.server.notification(notification).catch(error => logError("SimpleX channel", error))
|
|
})
|
|
registerTools(server, config.approve, async (name, input, call) => (configError === undefined ? link.call(name, input, call) : toolError(configError)), [replyTool])
|
|
server.registerTool("pre_tool_use", hookTool, async input => ({content: [{type: "text", text: hookOutput(link.approvedBy((input as {tool: string}).tool))}]}))
|
|
server.server.setNotificationHandler("notifications/claude/channel/permission_request", {params: permissionRequest}, params => {
|
|
if (configError !== undefined) return
|
|
const {request_id, tool_name, description, input_preview} = params as {[field in (typeof permissionFields)[number]]: string}
|
|
link.permission({id, requestId: request_id, toolName: tool_name, description, inputPreview: input_preview}).catch(error => logError("permission relay", error))
|
|
})
|
|
const transport = new StdioServerTransport(io.stdin, io.stdout)
|
|
transport.onclose = () => link.close()
|
|
await server.connect(transport)
|
|
if (configError === undefined) link.start()
|
|
}
|
|
|
|
class ServiceLink {
|
|
private connecting?: Promise<void>
|
|
private attach?: AbortController
|
|
private closed = false
|
|
private refused = false
|
|
private retry = firstRetry
|
|
private retryTimer?: NodeJS.Timeout
|
|
private readonly approvedTools = new WeakMap<AbortController, Map<string, string>>()
|
|
|
|
constructor(private readonly client: ServiceClient, private readonly request: SessionRequest, private readonly io: SessionIo, private readonly onLine: (line: unknown) => void) {}
|
|
|
|
// spec: spec/architecture.md#session-servicelink-approvedby
|
|
approvedBy(tool: string): string | undefined {
|
|
return this.attach === undefined ? undefined : this.approvedTools.get(this.attach)?.get(tool)
|
|
}
|
|
|
|
// spec: spec/architecture.md#session-servicelink-connect
|
|
connect(): Promise<void> {
|
|
if (this.refused) return Promise.reject(new Error(unattendedRun))
|
|
this.connecting ??= this.open().catch(error => {
|
|
this.connecting = undefined
|
|
throw error
|
|
})
|
|
return this.connecting
|
|
}
|
|
|
|
// spec: spec/architecture.md#session-servicelink-connect
|
|
start(): void {
|
|
this.connect().then(
|
|
() => (this.retry = firstRetry),
|
|
error => {
|
|
if (this.closed || this.refused) return
|
|
logError("SimpleX service", error)
|
|
if (!(error instanceof ProtocolError)) this.reconnect()
|
|
},
|
|
)
|
|
}
|
|
|
|
// spec: spec/architecture.md#session-servicelink-connect
|
|
close(): void {
|
|
this.closed = true
|
|
clearTimeout(this.retryTimer)
|
|
this.attach?.abort()
|
|
}
|
|
|
|
// spec: spec/architecture.md#session-servicelink-connect
|
|
private reconnect(): void {
|
|
if (this.closed) return
|
|
clearTimeout(this.retryTimer)
|
|
this.retryTimer = setTimeout(() => {
|
|
this.retry = Math.min(this.retry * 2, lastRetry)
|
|
this.start()
|
|
}, this.retry).unref()
|
|
}
|
|
|
|
// spec: spec/architecture.md#session-servicelink-permission
|
|
async permission(request: PermissionRequest): Promise<void> {
|
|
if (this.refused) return
|
|
await this.connect()
|
|
await this.client.request("POST", "/permission", request)
|
|
}
|
|
|
|
// spec: spec/architecture.md#session-servicelink-call
|
|
async call(name: ToolName, input: unknown, call: ToolCall): Promise<CallToolResult | undefined> {
|
|
for (let attempt = 1; ; attempt++) {
|
|
try {
|
|
return await this.forward(name, input, call)
|
|
} catch (error) {
|
|
if (call.signal.aborted) return undefined
|
|
if (attempt < callAttempts && error instanceof SocketError && error.status === unknownSessionStatus) continue
|
|
return toolError(this.refused ? unattendedRun : failureText(error))
|
|
}
|
|
}
|
|
}
|
|
|
|
// spec: spec/architecture.md#session-servicelink-forward
|
|
private async forward(name: ToolName, input: unknown, call: ToolCall): Promise<CallToolResult | undefined> {
|
|
const connection = this.connect()
|
|
await connection
|
|
let result: CallToolResult | null | undefined
|
|
try {
|
|
await this.client.stream("/call", {id: this.request.id, tool: name, input}, line => {
|
|
const parsed = line as CallLine
|
|
if ("progress" in parsed) call.progress(parsed.progress)
|
|
else result = parsed.result
|
|
}, call.signal)
|
|
} catch (error) {
|
|
if (!call.signal.aborted) this.disconnect(connection)
|
|
throw error instanceof SocketError ? error : new ServiceStoppedError()
|
|
}
|
|
if (result === undefined) {
|
|
this.disconnect(connection)
|
|
throw new ServiceStoppedError()
|
|
}
|
|
return result ?? undefined
|
|
}
|
|
|
|
// spec: spec/architecture.md#session-servicelink-disconnect
|
|
private disconnect(connection: Promise<void>): void {
|
|
if (this.connecting !== connection) return
|
|
this.connecting = undefined
|
|
this.attach?.abort()
|
|
this.attach = undefined
|
|
}
|
|
|
|
// spec: spec/architecture.md#session-servicelink-open
|
|
private async open(): Promise<void> {
|
|
await this.client.ensureService(this.io.version, this.io.spawnService)
|
|
await this.client.request("POST", "/session", this.request).catch(error => {
|
|
if (error instanceof SocketError && error.status === unattendedStatus) this.refused = true
|
|
throw error
|
|
})
|
|
if (this.closed) return
|
|
const controller = new AbortController()
|
|
this.attach?.abort()
|
|
this.attach = controller
|
|
await new Promise<void>((resolve, reject) => {
|
|
this.client
|
|
.stream("/attach", {id: this.request.id, pid: this.request.pid}, line => {
|
|
resolve()
|
|
const {tools} = line as AttachLine
|
|
if (tools !== undefined) this.approvedTools.set(controller, new Map(tools.map(({tool, approvedBy}) => [tool, approvedBy])))
|
|
this.onLine(line)
|
|
}, controller.signal)
|
|
.then(() => reject(new ServiceStoppedError()), reject)
|
|
.finally(() => {
|
|
if (this.attach === controller) {
|
|
this.attach = undefined
|
|
this.connecting = undefined
|
|
}
|
|
this.reconnect()
|
|
})
|
|
})
|
|
}
|
|
}
|
|
|
|
// spec: spec/architecture.md#session-failuretext
|
|
function failureText(error: unknown): string {
|
|
if (isNotRunning(error) || (error instanceof SocketError && error.status === stoppingStatus)) return serviceStopped
|
|
return errorText(error)
|
|
}
|
|
|
|
// spec: spec/api.md#plugin-results
|
|
function toolError(text: string): CallToolResult {
|
|
return {content: [{type: "text", text}], isError: true}
|
|
}
|
|
|
|
// spec: spec/api.md#plugin-tools
|
|
function hookOutput(approvedBy: string | undefined): string {
|
|
return approvedBy === undefined ? "" : JSON.stringify({hookSpecificOutput: {hookEventName: "PreToolUse", permissionDecision: "allow", permissionDecisionReason: `Approved for this session by ${approvedBy} in the session's SimpleX group.`}})
|
|
}
|
|
|
|
// spec: spec/architecture.md#session-channelnotification
|
|
function channelNotification({prompt, permission}: AttachLine): {method: string; params: {[key: string]: unknown}} | undefined {
|
|
if (prompt !== undefined) return {method: "notifications/claude/channel", params: {content: prompt.text, meta: {from: prompt.from, item: String(prompt.item), ...(prompt.file === undefined ? {} : {file: prompt.file}), ...(prompt.replyTo?.item === undefined ? {} : {reply_to: String(prompt.replyTo.item)}), ...(prompt.replyTo?.from === undefined ? {} : {reply_to_from: prompt.replyTo.from}), ...(prompt.edited === true ? {edited: "true"} : {})}}}
|
|
if (permission !== undefined) return {method: "notifications/claude/channel/permission", params: {request_id: permission.requestId, behavior: permission.behavior}}
|
|
return undefined
|
|
}
|