Coder Tasks have been removed from coder/coder, so the
`coder_report_task` MCP tool and the status reporting pipeline behind it
no longer do anything useful. This PR removes the tool and the code that
only existed to support it.
### Removed
- `codersdk/toolsdk`: `ToolNameReportTask`, `ReportTaskArgs`,
`ReportTask`, `Deps.report`, `WithTaskReporter`, and the `All` entry,
plus their tests.
- `coderd/mcp`: the remote MCP exclusion for `coder_report_task`.
- `coder exp mcp server`: the task reporter, the AgentAPI screen
watcher, the agent socket connection, and the `coder_report_task` skip
logic. The server now requires an authenticated user client, because
every remaining tool needs one.
- `coder exp mcp configure claude-code`: the
`mcp__coder__coder_report_task` allowed tool, the injected
`coder_report_task` CLAUDE.md prompt, the `report tasks properly`
history line, the default system prompt asking the agent to send task
status updates, and the `CODER_MCP_APP_STATUS_SLUG` /
`CODER_MCP_AI_AGENTAPI_URL` env written to the Claude MCP config.
- `cli/cliutil/queue.go`: only used by the reporter.
- `github.com/coder/agentapi-sdk-go` (and transitive `tmaxmax/go-sse`)
via `go mod tidy`.
- The "task reporting" mention in `docs/ai-coder/mcp-server.md`.
### Breaking: removed `coder exp` flags and env
`coder exp` is experimental. Any scripts that still pass these flags
will now fail with an unknown flag error. Env vars that are no longer
read are ignored.
| Command | Flag | Env |
|---|---|---|
| `coder exp mcp server` | `--app-status-slug` |
`CODER_MCP_APP_STATUS_SLUG` |
| `coder exp mcp server` | `--ai-agentapi-url` |
`CODER_MCP_AI_AGENTAPI_URL` |
| `coder exp mcp server` | `--socket-path` | `CODER_AGENT_SOCKET_PATH`
(still used by `coder agent` and `coder exp sync`) |
| `coder exp mcp configure claude-code` | `--claude-app-status-slug` |
`CODER_MCP_APP_STATUS_SLUG` |
| `coder exp mcp configure claude-code` | `--ai-agentapi-url` |
`CODER_MCP_AI_AGENTAPI_URL` |
`--claude-system-prompt` no longer has a default.
<details>
<summary>Intentionally kept</summary>
- **Workspace app status reporting** (`UpdateAppStatus` on the agent API
and agent socket, `agentsdk.PatchAppStatus` / `ProtoFromPatchAppStatus`,
the deprecated `PATCH /workspaceagents/me/app-status` endpoint): still
served by coderd and the agent and part of versioned protocols. With
this change, nothing in the CLI calls the agent socket `UpdateAppStatus`
client anymore. Removing it would need a separate protocol change.
- **`report_tasks` in
`coderd/templatebuilder/modules/{aider,amazon-q}`**: these catalog
entries mirror the input variables of pinned coder/registry module
versions, and the behavior lives in those modules. Dropping the variable
here would not disable it, because `amazon-q` defaults it to `true`. The
registry modules need a follow-up instead.
- **`UserClientOptional` on toolsdk tools**: other tools still set it,
and remote MCP still uses it.
- No CLI golden files or generated CLI docs changed, because `coder exp`
commands are hidden.
</details>
### Verification
- `go build ./...`
- `go test ./codersdk/toolsdk/... ./coderd/mcp/... ./cli/cliutil/...`
- `go test ./cli -run 'TestExpMcp|TestCommandHelp'`
- `golangci-lint run ./cli/... ./codersdk/toolsdk/... ./coderd/mcp/...`
(0 issues)
---
_Generated by Coder Agents._
Co-authored-by: coder[bot] <137810501+coder[bot]@users.noreply.github.com>
260 lines
8.1 KiB
Go
260 lines
8.1 KiB
Go
package mcp
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
stdslog "log/slog" //nolint:depguard // mcp.ServerOptions.Logger requires a *log/slog.Logger; slogHandler forwards to cdr.dev/slog.
|
|
"net/http"
|
|
|
|
"github.com/modelcontextprotocol/go-sdk/mcp"
|
|
"golang.org/x/xerrors"
|
|
|
|
"cdr.dev/slog/v3"
|
|
"github.com/coder/coder/v2/buildinfo"
|
|
"github.com/coder/coder/v2/codersdk"
|
|
"github.com/coder/coder/v2/codersdk/toolsdk"
|
|
)
|
|
|
|
const (
|
|
// MCPServerName is the name used for the MCP server.
|
|
MCPServerName = "Coder"
|
|
// MCPServerInstructions is the instructions text for the MCP server.
|
|
MCPServerInstructions = "Coder MCP Server providing workspace and template management tools"
|
|
|
|
// MCPEndpoint is the remote MCP HTTP endpoint path.
|
|
MCPEndpoint = codersdk.MCPEndpoint
|
|
)
|
|
|
|
// Server represents an MCP HTTP server instance
|
|
type Server struct {
|
|
Logger slog.Logger
|
|
|
|
// mcpServer is the underlying MCP server
|
|
mcpServer *mcp.Server
|
|
|
|
handler http.Handler
|
|
}
|
|
|
|
// NewServer creates a new MCP HTTP server
|
|
func NewServer(logger slog.Logger) (*Server, error) {
|
|
mcpSrv := mcp.NewServer(&mcp.Implementation{
|
|
Name: MCPServerName,
|
|
Version: buildinfo.Version(),
|
|
}, &mcp.ServerOptions{
|
|
Instructions: MCPServerInstructions,
|
|
Logger: stdslog.New(&slogHandler{logger: logger}),
|
|
})
|
|
|
|
// Stateless mode runs each request as its own short-lived session,
|
|
// omits Mcp-Session-Id, and answers GET and DELETE with 405, all
|
|
// permitted by the Streamable HTTP transport spec.
|
|
handler := mcp.NewStreamableHTTPHandler(func(*http.Request) *mcp.Server {
|
|
return mcpSrv
|
|
}, &mcp.StreamableHTTPOptions{
|
|
Stateless: true,
|
|
// Use application/json instead of SSE framing because Coder
|
|
// tools emit no notifications and do not need a stream.
|
|
JSONResponse: true,
|
|
// coderd often listens on loopback behind a reverse proxy,
|
|
// which trips the SDK's localhost DNS-rebinding check (loopback
|
|
// local address with a public Host header). The endpoint's
|
|
// bearer authentication is the relevant access control.
|
|
DisableLocalhostProtection: true,
|
|
})
|
|
|
|
return &Server{
|
|
Logger: logger,
|
|
mcpServer: mcpSrv,
|
|
handler: handler,
|
|
}, nil
|
|
}
|
|
|
|
// ServeHTTP implements http.Handler interface
|
|
func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
|
s.handler.ServeHTTP(w, r)
|
|
}
|
|
|
|
// Register all available MCP tools with the server excluding the ChatGPT
|
|
// search and fetch tools, which are redundant with the standard tools.
|
|
func (s *Server) RegisterTools(client *codersdk.Client, opts ...func(*toolsdk.Deps)) error {
|
|
if client == nil {
|
|
return xerrors.New("client cannot be nil: MCP HTTP server requires authenticated client")
|
|
}
|
|
|
|
// Create tool dependencies
|
|
toolDeps, err := toolsdk.NewDeps(client, opts...)
|
|
if err != nil {
|
|
return xerrors.Errorf("failed to initialize tool dependencies: %w", err)
|
|
}
|
|
|
|
for _, tool := range toolsdk.All {
|
|
if tool.Name == toolsdk.ToolNameChatGPTSearch || tool.Name == toolsdk.ToolNameChatGPTFetch {
|
|
continue
|
|
}
|
|
|
|
RegisterSDKTool(s.mcpServer, tool, toolDeps)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// RegisterPrompts registers all MCP prompt templates with the server.
|
|
func (s *Server) RegisterPrompts() {
|
|
for _, prompt := range toolsdk.AllPrompts {
|
|
RegisterSDKPrompt(s.mcpServer, prompt)
|
|
}
|
|
}
|
|
|
|
// ChatGPT tools are the search and fetch tools as defined in https://platform.openai.com/docs/mcp.
|
|
// We do not expose any extra ones because ChatGPT has an undocumented "Safety Scan" feature.
|
|
// In my experiments, if I included extra tools in the MCP server, ChatGPT would often - but not always -
|
|
// refuse to add Coder as a connector.
|
|
func (s *Server) RegisterChatGPTTools(client *codersdk.Client, opts ...func(*toolsdk.Deps)) error {
|
|
if client == nil {
|
|
return xerrors.New("client cannot be nil: MCP HTTP server requires authenticated client")
|
|
}
|
|
|
|
// Create tool dependencies
|
|
toolDeps, err := toolsdk.NewDeps(client, opts...)
|
|
if err != nil {
|
|
return xerrors.Errorf("failed to initialize tool dependencies: %w", err)
|
|
}
|
|
|
|
for _, tool := range toolsdk.All {
|
|
if tool.Name != toolsdk.ToolNameChatGPTSearch && tool.Name != toolsdk.ToolNameChatGPTFetch {
|
|
continue
|
|
}
|
|
|
|
RegisterSDKTool(s.mcpServer, tool, toolDeps)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// RegisterSDKTool registers a [toolsdk.GenericTool] with an MCP server.
|
|
func RegisterSDKTool(srv *mcp.Server, sdkTool toolsdk.GenericTool, tb toolsdk.Deps) {
|
|
if sdkTool.Schema.Properties == nil {
|
|
panic("developer error: schema properties cannot be nil")
|
|
}
|
|
|
|
inputSchema := map[string]any{
|
|
"type": "object",
|
|
"properties": sdkTool.Schema.Properties,
|
|
"additionalProperties": false,
|
|
}
|
|
if len(sdkTool.Schema.Required) > 0 {
|
|
inputSchema["required"] = sdkTool.Schema.Required
|
|
}
|
|
|
|
srv.AddTool(&mcp.Tool{
|
|
Name: sdkTool.Name,
|
|
Description: sdkTool.Description,
|
|
InputSchema: inputSchema,
|
|
// Set pointer-valued hints even when false so every hint
|
|
// remains explicit on the wire.
|
|
Annotations: &mcp.ToolAnnotations{
|
|
ReadOnlyHint: sdkTool.MCPAnnotations.ReadOnlyHint,
|
|
DestructiveHint: new(sdkTool.MCPAnnotations.DestructiveHint),
|
|
IdempotentHint: sdkTool.MCPAnnotations.IdempotentHint,
|
|
OpenWorldHint: new(sdkTool.MCPAnnotations.OpenWorldHint),
|
|
},
|
|
}, func(ctx context.Context, req *mcp.CallToolRequest) (*mcp.CallToolResult, error) {
|
|
result, err := sdkTool.Handler(ctx, tb, req.Params.Arguments)
|
|
if err != nil {
|
|
var validationErr *toolsdk.ArgumentValidationError
|
|
if !errors.As(err, &validationErr) {
|
|
return toolErrorResult(err.Error()), nil
|
|
}
|
|
content, marshalErr := json.Marshal(struct {
|
|
Error string `json:"error"`
|
|
ExpectedSchema map[string]any `json:"expectedSchema"`
|
|
}{
|
|
Error: validationErr.Error(),
|
|
ExpectedSchema: inputSchema,
|
|
})
|
|
if marshalErr != nil {
|
|
return toolErrorResult(xerrors.Errorf("marshal MCP tool argument validation response: %w", marshalErr).Error()), nil
|
|
}
|
|
return toolErrorResult(string(content)), nil
|
|
}
|
|
return &mcp.CallToolResult{
|
|
Content: []mcp.Content{
|
|
&mcp.TextContent{Text: string(result)},
|
|
},
|
|
}, nil
|
|
})
|
|
}
|
|
|
|
func toolErrorResult(message string) *mcp.CallToolResult {
|
|
return &mcp.CallToolResult{
|
|
Content: []mcp.Content{&mcp.TextContent{Text: message}},
|
|
IsError: true,
|
|
}
|
|
}
|
|
|
|
// RegisterSDKPrompt registers a [toolsdk.Prompt] with an MCP server.
|
|
func RegisterSDKPrompt(srv *mcp.Server, sdkPrompt toolsdk.Prompt) {
|
|
args := make([]*mcp.PromptArgument, 0, len(sdkPrompt.Arguments))
|
|
for _, arg := range sdkPrompt.Arguments {
|
|
args = append(args, &mcp.PromptArgument{
|
|
Name: arg.Name,
|
|
Description: arg.Description,
|
|
Required: arg.Required,
|
|
})
|
|
}
|
|
srv.AddPrompt(&mcp.Prompt{
|
|
Name: sdkPrompt.Name,
|
|
Description: sdkPrompt.Description,
|
|
Arguments: args,
|
|
}, func(_ context.Context, req *mcp.GetPromptRequest) (*mcp.GetPromptResult, error) {
|
|
text, err := sdkPrompt.Render(req.Params.Arguments)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return &mcp.GetPromptResult{
|
|
Description: sdkPrompt.Description,
|
|
Messages: []*mcp.PromptMessage{
|
|
{Role: "user", Content: &mcp.TextContent{Text: text}},
|
|
},
|
|
}, nil
|
|
})
|
|
}
|
|
|
|
type slogHandler struct {
|
|
logger slog.Logger
|
|
}
|
|
|
|
// The SDK logs several INFO lines per stateless request (session
|
|
// connect/disconnect), so only warnings and errors are forwarded.
|
|
func (*slogHandler) Enabled(_ context.Context, level stdslog.Level) bool {
|
|
return level >= stdslog.LevelWarn
|
|
}
|
|
|
|
func (h *slogHandler) Handle(ctx context.Context, record stdslog.Record) error {
|
|
fields := make([]slog.Field, 0, record.NumAttrs())
|
|
record.Attrs(func(attr stdslog.Attr) bool {
|
|
fields = append(fields, slog.F(attr.Key, attr.Value.Any()))
|
|
return true
|
|
})
|
|
switch {
|
|
case record.Level >= stdslog.LevelError:
|
|
h.logger.Error(ctx, record.Message, fields...)
|
|
case record.Level >= stdslog.LevelWarn:
|
|
h.logger.Warn(ctx, record.Message, fields...)
|
|
default:
|
|
h.logger.Info(ctx, record.Message, fields...)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (h *slogHandler) WithAttrs(attrs []stdslog.Attr) stdslog.Handler {
|
|
fields := make([]slog.Field, 0, len(attrs))
|
|
for _, attr := range attrs {
|
|
fields = append(fields, slog.F(attr.Key, attr.Value.Any()))
|
|
}
|
|
return &slogHandler{logger: h.logger.With(fields...)}
|
|
}
|
|
|
|
func (h *slogHandler) WithGroup(string) stdslog.Handler {
|
|
return h
|
|
}
|