package thin import ( "bufio" "context" "encoding/base64" "encoding/json" "net" "os" "path/filepath" "slices" "strings" "sync" "amadan.net/oficina/equipo/internal/runner/provider" "amadan.net/oficina/equipo/internal/runner/provider/claude" "amadan.net/oficina/equipo/internal/wire" "amadan.net/oficina/equipo/internal/runner" ) const maxToolFrame = 64 << 10 // ToolFunc runs one coordinator tool. useID is the provider's tool-use id // when the client sends one. The text goes back to the model. type ToolFunc func(ctx context.Context, name, useID string, args json.RawMessage) (text string, isError bool) // ToolReplyFunc runs one tool whose answer may carry an image too. type ToolReplyFunc func(ctx context.Context, name, useID string, args json.RawMessage) toolReply // toolReply is a tool's answer: its text and, for read_attachment on an // image, the image beside it (an MCP image content block). type toolReply struct { Text string IsError bool Image *toolImage } // toolImage is an image a tool returns, scaled for the model. type toolImage struct { MediaType string Data []byte } // textOnly is a ToolFunc as a ToolReplyFunc. func textOnly(call ToolFunc) ToolReplyFunc { if call == nil { return nil } return func(ctx context.Context, name, useID string, args json.RawMessage) toolReply { text, isError := call(ctx, name, useID, args) return toolReply{Text: text, IsError: isError} } } // toolSocket is the runner end of /tool/equipo.sock for one coordinator // process. It lists exactly the conversation's tools and Claude's // permission callback, which allows only those tools. type toolSocket struct { set toolSet call ToolReplyFunc Path string dir string listener *net.UnixListener cancel context.CancelFunc wg sync.WaitGroup peerUID func(fd int) (uint32, error) } // toolPeerUID reads a tool socket peer's user: SO_PEERCRED on Linux, // LOCAL_PEERCRED on a Mac (runner peer_*.go). Tests stand in. var toolPeerUID = runner.PeerUID // openToolSocket creates /coord-tool-*/equipo.sock, 0700 and 0600 // (on a Mac //s, toolsocket_layout.go). root must be a // private directory the model cannot read (toolRoot). func openToolSocket(ctx context.Context, root string, call ToolFunc) (*toolSocket, error) { return openToolSet(ctx, root, converseSet(call != nil), call) } // toolSet is what one process's tool socket serves: the tools it lists // beside the permission callback, the names it may call, and the // callback's answer (nil: no permission tool, as for Codex, which asks // through the app-server instead). type toolSet struct { current func() toolSet list []any names []string permission func(json.RawMessage) string } // converseSet is the coordinator's: its tools when it has any, and a // callback that allows only those. func converseSet(tools bool) toolSet { var names []string s := toolSet{} if tools { names = provider.ConverseTools() s.list, s.names = converseTools, names } s.permission = func(raw json.RawMessage) string { return permissionText(raw, names) } return s } func openToolSet(ctx context.Context, root string, set toolSet, call ToolFunc) (*toolSocket, error) { return openReplySet(ctx, root, set, textOnly(call)) } // openReplySet is openToolSet for tools whose answers may carry an image. func openReplySet(ctx context.Context, root string, set toolSet, call ToolReplyFunc) (*toolSocket, error) { dir, err := os.MkdirTemp(root, toolDirPrefix) if err != nil { return nil, err } fail := func(err error) (*toolSocket, error) { os.RemoveAll(dir); return nil, err } if err = os.Chmod(dir, 0700); err != nil { return fail(err) } path := filepath.Join(dir, toolSocketName) l, err := listenToolSocket(dir, path) if err != nil { return fail(err) } l.SetUnlinkOnClose(false) if err = os.Chmod(path, 0600); err != nil { l.Close() return fail(err) } ctx, cancel := context.WithCancel(ctx) s := &toolSocket{Path: path, dir: dir, listener: l, cancel: cancel, call: call, set: set, peerUID: toolPeerUID} context.AfterFunc(ctx, func() { l.Close() }) s.wg.Add(1) go s.accept(ctx) return s, nil } func (s *toolSocket) Close() { s.cancel() s.listener.Close() s.wg.Wait() os.RemoveAll(s.dir) } func (s *toolSocket) accept(ctx context.Context) { defer s.wg.Done() for { c, err := s.listener.AcceptUnix() if err != nil { return } // Only this user's processes may talk to the broker. raw, err := c.SyscallConn() uid, known := uint32(0), false if err == nil { _ = raw.Control(func(fd uintptr) { uid, err = s.peerUID(int(fd)); known = err == nil }) } if err != nil || !known || uid != uint32(os.Getuid()) { c.Close() continue } s.wg.Add(1) go func() { defer s.wg.Done() defer c.Close() stop := context.AfterFunc(ctx, func() { c.Close() }) defer stop() serveMCP(ctx, c, s.set, s.call) }() } } type mcpRequest struct { JSONRPC string `json:"jsonrpc"` ID json.RawMessage `json:"id,omitempty"` Method string `json:"method"` Params json.RawMessage `json:"params,omitempty"` } // toolSchema is a JSON Schema object; required is always an array (a // null there is not valid JSON Schema and the CLI refuses the tool list). func toolSchema(props map[string]any, required ...string) map[string]any { if required == nil { required = []string{} } return map[string]any{"type": "object", "properties": props, "required": required, "additionalProperties": false} } var str = map[string]string{"type": "string"} // converseTools are the coordinator's tools as the model sees them. The // descriptions are for the model; people never read them. var converseTools = []any{ map[string]any{"name": wire.ToolRequestAccess, "description": "Propose an access request for an unreachable repository. The person confirms before filing; never retry unprompted. Prefer one repository; namespace only if explicitly requested. Role defaults to agent.", "inputSchema": toolSchema(map[string]any{"target": str, "role": str, "reason": str}, "target", "reason")}, map[string]any{"name": "status", "description": "Read-only: this person's runner, model connections, current projects, the repositories you can add (can_add), the namespaces you can create repositories in (create_in, with home for unrelated new work), and the team's active specialists (specialists: id, profile, name, brief, and scope, team or the one project it works on; pass the id as start_task's specialist). Call it before choosing where work goes. runner.tools says whether the runner's pinned preview scanner is installed and matches its pin (ok, missing, mismatch, unpinned, or unknown when the runner does not say): a preview that failed for its scanner needs the runner fixed or updated, not another try. runner.tools.carlos says whether its CARLOS command line tool is current enough for previews and sites (ok, outdated, missing) and carlos_version which release it is: outdated or missing needs the person to update it, not another try. runner.tools.renderer, only on a runner that has the page renderer, says whether its pinned browser is installed, matches its pin and has rendered its check page since the runner started (ok, missing, mismatch, unpinned): anything but ok needs the runner updated, not another try.", "inputSchema": toolSchema(map[string]any{})}, map[string]any{"name": "find", "description": "Read-only: find which repository an app, product or feature lives in, by name, alias or keyword (for example Woodstar). Returns candidates with reasons, or says nothing Equipo's agent can reach matches.", "inputSchema": toolSchema(map[string]any{"query": str}, "query")}, map[string]any{"name": "search_code", "description": "Read-only: search a repository's default branch for a fixed string, case insensitive. Returns path:line: text, bounded.", "inputSchema": toolSchema(map[string]any{"repo": str, "query": str}, "repo", "query")}, map[string]any{"name": "read_file", "description": "Read-only: read a file from a repository's default branch with line numbers (up to 300 lines from start), or list a directory (empty path is the root). For a file the person attached, repo is \"attachments\" and path is the one given with their message.", "inputSchema": toolSchema(map[string]any{"repo": str, "path": str, "start": map[string]string{"type": "integer"}}, "repo", "path")}, map[string]any{"name": "add_project", "description": "Work in an existing repository from can_add, for example oficina/equipo. Use the named project or clear continuation. If ambiguous, ask_person with placement choices first.", "inputSchema": toolSchema(map[string]any{"repo": str}, "repo")}, map[string]any{"name": "create_project", "description": "Create a new private repository for new work that fits no existing repository, in a namespace from create_in: the related namespace when it is obvious, otherwise home (the team's setting for new projects). name is lower case letters, digits, dots and dashes. Requires the person to choose New project on a placement card, unless their current message explicitly requests a new project.", "inputSchema": toolSchema(map[string]any{"namespace": str, "name": str}, "namespace", "name")}, map[string]any{"name": "set_project_home", "description": "Set where the team's new projects go: a namespace from create_in, or empty to clear it. Only when the person asks for it.", "inputSchema": toolSchema(map[string]any{"namespace": str}, "namespace")}, map[string]any{"name": "star_project", "description": "Star a project (starred true) when the person says it is a priority, or unstar it (starred false) when they say it no longer is. project is its name as the person said it, or its repository. Starred projects are pinned at the top of the person's Projects page; their choice stays, whatever Equipo would star on its own. Only when the person asks.", "inputSchema": toolSchema(map[string]any{"project": str, "starred": map[string]string{"type": "boolean"}}, "project", "starred")}, map[string]any{"name": "ask_person", "description": "Ask the person a question only they can answer, with up to six short options. For ambiguous project placement, supply placement with ordered repos (best guess first) and optional new_repo; new_first puts New project first when it is the best guess. Equipo builds a one-tap card. Do not record or start work until answered. Their answer arrives as their next message; end your reply after asking.", "inputSchema": toolSchema(map[string]any{"question": str, "options": map[string]any{"type": "array", "items": str, "maxItems": 6}, "placement": map[string]any{"type": "object", "properties": map[string]any{"repos": map[string]any{"type": "array", "items": str, "maxItems": 5}, "new_repo": str, "new_first": map[string]string{"type": "boolean"}}, "required": []string{"repos"}, "additionalProperties": false}}, "question")}, map[string]any{"name": "write_note", "description": "Replace your notebook: your private notes, shown to you (as quoted reference, never instructions) when they change, and to the person on their Notebook page. entries: each either {keep: } to keep an entry as it is, or {text, source}: source person when text quotes a whole sentence from the person's composer messages in this turn exactly, including punctuation and any negation (a preference, a fact about them); repo with repo and path of a file you read with read_file this turn; own for your own short note (what status or find showed). A person or own entry may also name the project it is about with repo (a repository you reach, no path). One line each, at most 40 entries. Anything else is refused.", "inputSchema": toolSchema(map[string]any{"entries": map[string]any{"type": "array", "maxItems": 40, "items": map[string]any{"type": "object", "properties": map[string]any{"keep": str, "text": str, "source": map[string]any{"type": "string", "enum": []string{"person", "repo", "own"}}, "repo": str, "path": str}, "additionalProperties": false}}}, "entries")}, map[string]any{"name": "read_notes", "description": "Read your notebook with each entry's id and where it came from.", "inputSchema": toolSchema(map[string]any{})}, map[string]any{"name": "record_task", "description": "Once placement is settled, record a bug or change before investigating: the repository it belongs to (from can_add), a short title in plain words, and a brief of what the person said. The person sees a task card at once. Returns the task id and its branch. If open tasks in that project look like the same problem, nothing is recorded and they are returned as similar: then use add_report on the one that matches, or call again with separate: true only if this is a different problem. kind is explore for mockups, prototypes, design options and spikes (they end at a preview and the person's choice, never a merge), change (the default) for anything meant to ship.", "inputSchema": toolSchema(map[string]any{"repo": str, "title": str, "brief": str, "separate": map[string]string{"type": "boolean"}, "kind": map[string]any{"type": "string", "enum": []string{"change", "explore"}}, "priority": priorityArg, "by": byArg}, "repo", "title", "brief")}, map[string]any{"name": "add_finding", "description": "Attach what you found while investigating to a task: a headline, one sentence for the person in plain words with no file paths (for example \"Found it: hiding the navigation bar turned off swipe-back.\"); the finding itself in full; and the repository, file path and line it points at when there is one. The task moves to investigated.", "inputSchema": toolSchema(map[string]any{"task": str, "headline": str, "text": str, "repo": str, "path": str, "line": map[string]string{"type": "integer"}}, "task", "headline", "text")}, map[string]any{"name": "start_task", "description": "Hand a recorded task to Engineering, who changes the code on the task's own branch and pushes it to Amadan. brief is what to change and why, from your findings. specialist is optional: the id of an active specialist from status that makes changes (Design) and covers the task's project or the team, to do the task instead of Engineering; its fix rounds and retries stay with it. Never merges and never opens a pull request. Call it once per task.", "inputSchema": toolSchema(map[string]any{"task": str, "brief": str, "priority": priorityArg, "by": byArg, "specialist": str}, "task", "brief")}, map[string]any{"name": "read_task", "description": "Read a task: its stage, findings, steps (state, branch, commit, summary) and the person's notes on it.", "inputSchema": toolSchema(map[string]any{"task": str}, "task")}, map[string]any{"name": "cancel_task", "description": "Cancel a task when the person asks; a running step stops.", "inputSchema": toolSchema(map[string]any{"task": str}, "task")}, map[string]any{"name": "add_report", "description": "Add the person's new report of a problem that is already an open task (from record_task's similar list, or one you know) to that task, instead of recording a duplicate. text is what the person said. The person sees the task card.", "inputSchema": toolSchema(map[string]any{"task": str, "text": str}, "task", "text")}, map[string]any{"name": "hold_merge", "description": "Stop Equipo merging this task on its own when you have a concrete reason it needs the person's look (reason: one plain sentence, shown on their merge card). It can only make Equipo more careful: the person's own Merge still merges. There is no tool to lift a hold.", "inputSchema": toolSchema(map[string]any{"task": str, "reason": str}, "task", "reason")}, map[string]any{"name": "set_merge_policy", "description": "Record how Equipo merges a project, from what the person said (words: their sentence). mode is rules (merge on its own when every rule holds) or ask (ask before every merge); max_lines and max_files bound a merge without checks; main_ships is yes or no (does merging to main ship to users); add_sensitive adds path globs that always ask. A stricter change applies at once; a looser one waits for the person to tap Save on a card.", "inputSchema": toolSchema(map[string]any{"project": str, "words": str, "mode": str, "max_lines": map[string]any{"type": "integer"}, "max_files": map[string]any{"type": "integer"}, "main_ships": str, "add_sensitive": map[string]any{"type": "array", "items": str}}, "project", "words")}, map[string]any{"name": "propose_specialist", "description": "Ask the person to add a specialist to their team, from Equipo's fixed menu, when the work needs one that status does not list. Two profiles. research-v1, when the person wants something researched on the public web: it reads public web pages Equipo fetches for a task and reports what they say, and never reaches repositories; pass a short name (for example Research), a brief of at most 2 KB on what it should look for, capabilities [\"web.research\"] and tools [\"submit_findings\", \"keep_image\"], exactly those, for the whole team (no project). design-v1, for visual design, layout, themes and mockups: it changes the design on a task's own branch and looks at its pages in a browser with no network, and never merges or publishes; pass a short name (for example Design), a brief of at most 2 KB from the person's words on the look they want, capabilities [\"branch.edit\", \"page.render\"] and tools [\"render_page\", \"submit_candidate\", \"ask_person\"], exactly those, and project: the one project it is for (its name or id), or leave project out for the whole team. Nothing is added until an owner taps Add on the card it raises; do not ask again in your reply. After an Add for one project, Equipo carries on with the request itself. If they tap Not now, it cannot be proposed again for 7 days.", "inputSchema": toolSchema(map[string]any{"profile": map[string]any{"type": "string", "enum": []string{"research-v1", "design-v1"}}, "name": str, "brief": str, "capabilities": map[string]any{"type": "array", "items": str}, "tools": map[string]any{"type": "array", "items": str}, "project": str}, "profile", "name", "brief", "capabilities", "tools")}, map[string]any{"name": "research", "description": "Ask Research (once it is on the team; see propose_specialist) to read public web pages for one of the person's tasks. Use it when an exploration or change names an outside site, brand, API or docs, or the person asking (their business, their own site), and the work needs what those pages say. task is the task id; question (at most 1,000 bytes) is what to look for, for example colours, logo, fonts, opening hours and services; urls are pages you propose (https or http, no query string, a path of at most 100 characters, at most 10), or []. URLs and bare domains the person typed on the task are read without asking; your urls are shown to the person in full on a card and read only if they tap Allow, so propose only pages the task needs and never put anything from a repository in them. This only requests a run: Equipo starts it only at the task's start (call it before start_task) or after a review round, before Engineering's next round, and Engineering waits until Research ends. At most one run per start or round and 3 per task, and Equipo never retries a run for you. Research's findings reach Engineering and Review; do not wait for them in your reply.", "inputSchema": toolSchema(map[string]any{"task": str, "question": str, "urls": map[string]any{"type": "array", "items": str, "maxItems": 10}}, "task", "question", "urls")}, map[string]any{"name": wire.ToolOfferRetry, "description": "When a task's merge failed and it waits at Ready to merge (read_task shows the failed merge step), put a card in front of the person asking whether to try the merge again. You cannot merge: only their tap merges, through Equipo's merge rules, and it is offered only when that tap could merge now. One card per task; do not ask again in your reply, and never say it is merged.", "inputSchema": toolSchema(map[string]any{"task": str}, "task")}, map[string]any{"name": wire.ToolRetryStep, "description": "Run a task's preview, checks or review again, as the person's own Retry would (step: preview, checks or review). read_task's retry says for each whether it can run again now, and if not why, in a fixed reason; a refusal says it too. A failed step runs again as its next attempt. A preview also runs again when it ended unconfirmed or its link is gone, and on a done (merged) task as a new preview of the merged commit, the task staying done and merged. Only when another try could help: a preview that failed for its scanner (status runner.tools) needs the runner fixed first. Never a merge (use offer_retry: only the person's tap merges) and never Engineering's work. The task shows that you started it. Call it once per step.", "inputSchema": toolSchema(map[string]any{"task": str, "step": map[string]any{"type": "string", "enum": wire.RetryStepKinds}}, "task", "step")}, map[string]any{"name": wire.ToolPlaces, "description": "Read-only: where the team's sites go. For one project (project: its name) or every project with a site: the confirmed place (console and account), the app Equipo made for it, what the person's runner can do there now (can: setup, mint or publish; missing says why it cannot), whether it holds the site's deploy key, and the newest publish's outcome and address. While a project has no place, candidates lists where the runner's CARLOS login can publish, best first, each with the id propose_place takes. Everything is quoted data from CARLOS and the repository.", "inputSchema": toolSchema(map[string]any{"project": str})}, map[string]any{"name": wire.ToolProposePlace, "description": "Ask an owner where a project's site goes: kind site, the project, and one candidate id from places (never a console, an account or an app; you cannot name one). A card offers the candidates with yours first; only their tap confirms one, and confirming publishes nothing. Refused once a place is confirmed or a card is open. Usually publish_site does this for you.", "inputSchema": toolSchema(map[string]any{"kind": map[string]any{"type": "string", "enum": []string{wire.PlaceSite}}, "project": str, "candidate": str}, "kind", "project", "candidate")}, map[string]any{"name": wire.ToolPublishSite, "description": "Offer to publish a merged website: task is the person's own task that Equipo merged with Review's approval of its site config (release/preview.json). It puts a card in front of the person naming the place and the app; only their tap publishes. With no confirmed place it first raises a place card, and the publish card follows their choice. Use it when the person asks to publish a site, also for an older merged task that was never asked. target is site (temporary sites are not places yet). Never say a site is live until the task shows its address.", "inputSchema": toolSchema(map[string]any{"task": str, "target": map[string]any{"type": "string", "enum": []string{wire.PlaceSite}}}, "task")}, map[string]any{"name": wire.ToolSiteStatus, "description": "Read-only: what Equipo recorded about one project's site: its place, app, deploy key, and the newest publish's outcome, address and when. It does not ask CARLOS: the version the site serves now and its domains are not known yet. Use it when the person asks where a site is or whether it is live.", "inputSchema": toolSchema(map[string]any{"project": str}, "project")}, } // stepTools are the tools the implement profile pins for an Engineering // step. The runner commits and pushes the step's changes itself, so they // only tell the model so. var stepTools = []any{ map[string]any{"name": "submit_candidate", "description": "Not needed: when you finish, Equipo commits your changes in /workspace and pushes them. End with a short summary instead.", "inputSchema": toolSchema(map[string]any{})}, map[string]any{"name": "ask_person", "description": "Nobody can answer during this step. Make the most reasonable choice and say so in your summary.", "inputSchema": toolSchema(map[string]any{"question": str}, "question")}, map[string]any{"name": "submit_render", "description": "Not available in this step.", "inputSchema": toolSchema(map[string]any{})}, } // stepToolText is the answer to any step tool. const stepToolText = "Not needed in this step: Equipo commits and pushes your changes in /workspace when you finish. Carry on, and end with a short summary of what you changed and why." // designTools are the tools the design_step profile pins for a Design // step: exactly design-v1's (provider.DesignTools). The Design step // answers them (designstep.Attempt): render_page behind the instance's // render check, submit_candidate's options, and ask_person's fixed // reply; the runner commits and pushes the work itself, as // Engineering's. var designTools = []any{ map[string]any{"name": "render_page", "description": "Render pages of the task's site in a browser: tree base (the task's base commit) or work (your workspace now); compare true renders both trees, whichever tree you name or none, and diffs them. Each capture is a PNG in /render/, read-only to you; open it with Read.", "inputSchema": toolSchema(map[string]any{"tree": map[string]any{"type": "string", "enum": []string{"base", "work"}}, "pages": map[string]any{"type": "array", "minItems": 1, "maxItems": 6, "items": toolSchema(map[string]any{"path": str, "viewport": map[string]any{"type": "string", "enum": []string{"phone", "tablet", "desktop"}}, "full_page": map[string]string{"type": "boolean"}}, "path", "viewport")}, "compare": map[string]string{"type": "boolean"}}, "pages")}, map[string]any{"name": "submit_candidate", "description": "Submit your options: for each, in the order of the options page, its name and the captures that show it best, by the file names render_page gave under /render/ in this step. At most 4 options and 12 captures in all; a later call replaces an earlier one. Equipo still commits and pushes your workspace when you finish.", "inputSchema": toolSchema(map[string]any{"options": map[string]any{"type": "array", "maxItems": wire.MaxDesignOptions, "items": toolSchema(map[string]any{"name": str, "captures": map[string]any{"type": "array", "items": str, "maxItems": wire.MaxDesignCaptures}}, "name", "captures")}}, "options")}, map[string]any{"name": "ask_person", "description": "Nobody can answer during this step. Make the most reasonable choice, build it, and say so in your summary.", "inputSchema": toolSchema(map[string]any{"question": str}, "question")}, } // designToolNames are designTools' names, in order. var designToolNames = []string{"render_page", "submit_candidate", "ask_person"} // designRun is a Design step's run on binding b: the design_step policy // (design-v1's tools, Engineering's native tools and /render read-only, // claude.DesignPermission) with prompt, its tools answered by call. The // caller sets render, the step's capture directory. func designRun(b runner.AccountBinding, prompt string, call ToolFunc) specialistRun { return specialistRun{action: provider.DesignStepAction, binding: b, tools: designTools, names: designToolNames, permission: claude.DesignPermission, call: call, prompt: prompt} } // serveMCP answers JSON-RPC lines until the peer closes. func serveMCP(ctx context.Context, c net.Conn, set toolSet, call ToolReplyFunc) { r := bufio.NewReaderSize(c, maxToolFrame+1) enc := json.NewEncoder(c) initialized := false for { line, err := r.ReadSlice('\n') if err != nil || len(line) > maxToolFrame { return } var q mcpRequest if json.Unmarshal(line, &q) != nil || q.JSONRPC != "2.0" { return } if len(q.ID) == 0 { continue } active := set if set.current != nil { active = set.current() } reply := map[string]any{"jsonrpc": "2.0", "id": q.ID} switch q.Method { case "initialize": var p struct { ProtocolVersion string `json:"protocolVersion"` } _ = json.Unmarshal(q.Params, &p) if !slices.Contains([]string{"2024-11-05", "2025-03-26", "2025-06-18"}, p.ProtocolVersion) { p.ProtocolVersion = "2025-06-18" } initialized = true reply["result"] = map[string]any{"protocolVersion": p.ProtocolVersion, "capabilities": map[string]any{"tools": map[string]any{}}, "serverInfo": map[string]any{"name": "equipo-runner", "version": "2"}} case "ping": reply["result"] = map[string]any{} case "tools/list": if !initialized { reply["error"] = map[string]any{"code": -32600, "message": "not initialized"} break } tools := slices.Clone(active.list) if active.permission != nil { permission := map[string]any{"name": "permission", "inputSchema": map[string]any{"type": "object", "properties": map[string]any{"tool_name": map[string]string{"type": "string"}, "tool_use_id": map[string]string{"type": "string"}, "input": map[string]string{"type": "object"}}, "required": []string{"tool_name", "input"}, "additionalProperties": false}} tools = append([]any{permission}, tools...) } reply["result"] = map[string]any{"tools": tools} case "tools/call": var p struct { Name string `json:"name"` Arguments json.RawMessage `json:"arguments"` Meta map[string]any `json:"_meta"` } if !initialized || json.Unmarshal(q.Params, &p) != nil { reply["error"] = map[string]any{"code": -32602, "message": "unavailable"} break } if p.Name == "permission" && active.permission != nil { reply["result"] = map[string]any{"content": []any{map[string]string{"type": "text", "text": active.permission(p.Arguments)}}} break } if call == nil || !slices.Contains(active.names, p.Name) { reply["error"] = map[string]any{"code": -32602, "message": "unavailable"} break } useID, _ := p.Meta["claudecode/toolUseId"].(string) if len(p.Arguments) == 0 || string(p.Arguments) == "null" { p.Arguments = json.RawMessage("{}") } out := call(ctx, p.Name, useID, p.Arguments) content := []any{map[string]string{"type": "text", "text": out.Text}} if out.Image != nil { content = append(content, map[string]string{"type": "image", "data": base64.StdEncoding.EncodeToString(out.Image.Data), "mimeType": out.Image.MediaType}) } reply["result"] = map[string]any{"content": content, "isError": out.IsError} default: reply["error"] = map[string]any{"code": -32601, "message": "unavailable"} } if enc.Encode(reply) != nil { return } } } // permissionText allows only the conversation's own Equipo tools (names, // the lane's); every other request (native tools, the other lane's // tools, anything unexpected) is denied. func permissionText(raw json.RawMessage, names []string) string { var in struct { ToolName string `json:"tool_name"` Input json.RawMessage `json:"input"` } text := `{"behavior":"deny","message":"Only Equipo's own tools are available to the coordinator."}` if json.Unmarshal(raw, &in) == nil && strings.HasPrefix(in.ToolName, "mcp__equipo__") && slices.Contains(names, strings.TrimPrefix(in.ToolName, "mcp__equipo__")) { allow, _ := json.Marshal(map[string]any{"behavior": "allow", "updatedInput": in.Input}) text = string(allow) } return text } // priorityArg and byArg are record_task's and start_task's scheduler // fields (connectors spec ยง6): set only from what the person said, when // the task is created; the person alone makes a task urgent or changes // them later. var ( priorityArg = map[string]any{"type": "string", "enum": []string{"low", "normal"}, "description": "low when the person said it can wait, normal otherwise (the default). Never urgent: only the person marks a task urgent."} byArg = map[string]any{"type": "string", "description": "A deadline the person gave, as a date (2026-11-20) or a time (RFC 3339). Leave it out when they gave none."} )