// Package tools is the stdio MCP server that runs inside each container. // Its tools only check their input; the bot sees the calls over ACP and does the work. package tools import ( "bufio" "encoding/json" "fmt" "io" "os" "path/filepath" "strings" "sync" "time" ) const ( ServerName = "slackerbot" SendFile = "send_file" ) const sendFileHelp = "Send a file to the user in Slack: images, videos, PDFs, archives, reports or anything else " + "they should see or download. Prefer it to pasting long output. The file must be under %s and at most %d MB. " + "It's uploaded into the conversation when your turn ends, so mention it in your reply. " + "At most a few files per turn." const instructions = `This container runs NixOS with only a few tools installed. Nix is available with flakes, and builds run through the host. Use it for every toolchain and dependency: - For a new project, write a flake.nix with a devShells.default that provides everything the project needs (and packages.default if it builds something), then run commands with ` + "`nix develop -c `" + `. - In an existing project without a flake.nix, add one before installing anything. - Flakes only see files tracked by git, so ` + "`git init`" + ` and ` + "`git add`" + ` new files, including flake.nix and flake.lock, before building. - For a one-off tool, use ` + "`nix shell nixpkgs# -c `" + `. - Don't install things globally (nix-env, nix profile, pip install --user, npm install -g): only the home folder survives a restart. - The host may garbage-collect build outputs, so rebuild instead of relying on old result links.` const commandNote = " It's the same as the Slack command `%s`, and runs with the permissions of the person whose message you're answering." const ( defaultWait = time.Minute pollEvery = 200 * time.Millisecond // A reply older than this when a call starts belongs to an earlier call that gave up. staleAfter = 30 * time.Second ) type Server struct { Home string MaxMB int64 // How long a command waits for the bot. Zero means a minute. Wait time.Duration } type msg struct { JSONRPC string `json:"jsonrpc"` ID json.RawMessage `json:"id,omitempty"` Method string `json:"method,omitempty"` Params json.RawMessage `json:"params,omitempty"` Result any `json:"result,omitempty"` Error *rpcError `json:"error,omitempty"` } type rpcError struct { Code int `json:"code"` Message string `json:"message"` } func (s *Server) Serve(in io.Reader, out io.Writer) error { sc := bufio.NewScanner(in) sc.Buffer(make([]byte, 1<<20), 16<<20) enc := json.NewEncoder(out) var mu sync.Mutex var wg sync.WaitGroup defer wg.Wait() write := func(reply msg) error { mu.Lock() defer mu.Unlock() return enc.Encode(reply) } for sc.Scan() { var m msg if json.Unmarshal(sc.Bytes(), &m) != nil || len(m.ID) == 0 { continue } reply := msg{JSONRPC: "2.0", ID: m.ID} // Commands wait on the bot, so they mustn't hold up other requests. if c, args, ok := s.commandCall(m); ok { wg.Add(1) go func() { defer wg.Done() reply.Result = toolResult(s.await(c, args)) _ = write(reply) }() continue } reply.Result, reply.Error = s.handle(m) if err := write(reply); err != nil { return err } } return sc.Err() } func toolResult(text string, isErr bool) map[string]any { return map[string]any{"content": []any{map[string]string{"type": "text", "text": text}}, "isError": isErr} } func (s *Server) commandCall(m msg) (SlackCommand, string, bool) { if m.Method != "tools/call" { return SlackCommand{}, "", false } var p struct { Name string `json:"name"` Arguments json.RawMessage `json:"arguments"` } _ = json.Unmarshal(m.Params, &p) c, ok := commandNamed(p.Name) return c, argsOf(p.Arguments), ok } func (s *Server) await(c SlackCommand, args string) (string, bool) { if c.Missing(args) { return "args is required: " + c.Args, true } wait := s.Wait if wait == 0 { wait = defaultWait } start := time.Now() for { if r, ok := claimReply(replyDir(s.Home), replyPrefix(c.Name, args), start); ok { return r.Text, r.Error } if time.Since(start) > wait { return "slackerbot didn't answer in time, so it may not have run. Its master may be too old for this tool, " + "or the home folder may be full. Ask the user to send the command in Slack instead: " + c.Text(args), true } time.Sleep(pollEvery) } } // claimReply takes a reply by deleting it, so two waiting calls can't both get it. // The bot writes a file in one go, so one that doesn't parse yet is still being written. func claimReply(dir, prefix string, since time.Time) (Reply, bool) { entries, _ := os.ReadDir(dir) for _, e := range entries { if !strings.HasPrefix(e.Name(), prefix) { continue } p := filepath.Join(dir, e.Name()) info, err := e.Info() if err != nil { continue } if info.ModTime().Before(since.Add(-staleAfter)) { _ = os.Remove(p) continue } data, err := os.ReadFile(p) var r Reply if err != nil || json.Unmarshal(data, &r) != nil { continue } if os.Remove(p) == nil { return r, true } } return Reply{}, false } func (s *Server) handle(m msg) (any, *rpcError) { switch m.Method { case "initialize": var p struct { ProtocolVersion string `json:"protocolVersion"` } _ = json.Unmarshal(m.Params, &p) return map[string]any{ "protocolVersion": p.ProtocolVersion, "capabilities": map[string]any{"tools": map[string]any{}}, "serverInfo": map[string]string{"name": ServerName, "version": "1"}, "instructions": instructions, }, nil case "ping": return map[string]any{}, nil case "tools/list": return map[string]any{"tools": s.tools()}, nil case "tools/call": var p struct { Name string `json:"name"` Arguments struct { Path string `json:"path"` } `json:"arguments"` } _ = json.Unmarshal(m.Params, &p) if p.Name != SendFile { return nil, &rpcError{-32602, "unknown tool " + p.Name} } text, isErr := "queued", false if err := s.Check(p.Arguments.Path); err != nil { text, isErr = err.Error(), true } return toolResult(text, isErr), nil } return nil, &rpcError{-32601, "method not found: " + m.Method} } func (s *Server) tools() []any { list := []any{map[string]any{ "name": SendFile, "description": fmt.Sprintf(sendFileHelp, s.Home, s.MaxMB), "inputSchema": map[string]any{ "type": "object", "properties": map[string]any{ "path": map[string]string{"type": "string", "description": "Path of the file, e.g. " + s.Home + "/out/chart.png"}, "comment": map[string]string{"type": "string", "description": "Optional message posted with the file"}, }, "required": []string{"path"}, }, }} for _, c := range Commands { schema := map[string]any{"type": "object", "properties": map[string]any{}} if c.Args != "" { schema["properties"] = map[string]any{"args": map[string]string{"type": "string", "description": c.Args}} } if c.Required { schema["required"] = []string{"args"} } usage := c.Verb if c.Args != "" { usage += " " } list = append(list, map[string]any{ "name": c.Name, "description": c.Help + fmt.Sprintf(commandNote, usage), "inputSchema": schema, }) } return list } func (s *Server) Check(path string) error { if path == "" { return fmt.Errorf("path is required") } if !filepath.IsAbs(path) { path = filepath.Join(s.Home, path) } real, err := filepath.EvalSymlinks(path) if err != nil { return fmt.Errorf("can't find %s", path) } home := filepath.Clean(s.Home) if h, err := filepath.EvalSymlinks(home); err == nil { home = h } if !strings.HasPrefix(real, home+"/") { return fmt.Errorf("%s isn't under %s; copy it there first", path, s.Home) } st, err := os.Stat(real) if err != nil { return err } if !st.Mode().IsRegular() { return fmt.Errorf("%s isn't a regular file (zip a folder first)", path) } if st.Size() == 0 { return fmt.Errorf("%s is empty", path) } if st.Size() > s.MaxMB<<20 { return fmt.Errorf("%s is %d MB, over the %d MB limit", path, st.Size()>>20, s.MaxMB) } return nil }