Files
coder/agent/x/agentmcp/api_internal_test.go
T
Jeremy RuppelandCoder Agents e9429903d4 fix(agent): launch stdio MCP servers in the workspace dir (#29153)
## Problem

stdio MCP servers declared in `.mcp.json` were launched from the agent's
own working directory, which is unspecified and often a temp dir
(observed `/tmp/coder.*`). Relative paths in a server's `Args` (for
example a language server `-workspace ./site/`) resolved against that
temp dir instead of the workspace, so:

- `typescript-language-server` failed immediately: the resolved
`./site/` did not exist under the temp cwd.
- `go-language-server` connected but gopls rooted at the temp dir, so
workspace symbol lookups failed while per-file hover still worked.

The agent log showed `connection closed: calling "initialize": client is
closing: EOF`.

<img width="682" height="606" alt="Screenshot 2026-09-09 at 5 33 58 PM"
src="https://github.com/user-attachments/assets/650f1305-d807-406e-864e-e347e9a4c52d"
/>

## Fix

Launch stdio MCP servers in the workspace working directory instead of
inheriting the agent's cwd.

- `agent/agent.go`: hoist a single `workingDirFn` closure (reads
`a.manifest.Load().Directory`, `""` before the first manifest) and reuse
it for the process API, MCP manager, and context config/manager wiring.
- `agent/x/agentmcp/manager.go`: `Manager` gains a `workingDir func()
string`; `createTransport` sets `cmd.Dir = m.resolveWorkingDir(ctx)` for
the stdio path. `resolveWorkingDir` routes through
`usershell.ResolveWorkingDirectory`, the same helper SSH sessions and
the process API use, so the three cannot drift: an existing configured
dir is used, otherwise the user's home dir. Returns `""` (inherit) only
when the callback is nil or empty.

`.mcp.json` is unchanged. Storybook is untouched.

## Tests

- `TestCreateTransport_StdioSetsWorkingDir`: constructs the manager via
`NewManager` and asserts the stdio transport's `Command.Dir` is the
workspace dir.
- `TestResolveWorkingDir`: table cases for nil/empty callback (inherit),
existing dir, missing dir, and a path that is a file (both fall back to
home).

## Checks

`make fmt`, `make lint`, and `go test ./agent/x/agentmcp/` all pass.

<details>
<summary>Design notes and alternatives considered</summary>

First-principles contract: MCP servers should launch in the workspace
working directory, matching existing docs and agent subsystem behavior,
not the config directory that declares them.

An earlier iteration set `cmd.Dir` from the config file's directory;
review found that fragile (global config locations, `$HOME` semantics).
It was replaced with the workspace-dir callback that reuses
`usershell.ResolveWorkingDirectory` for consistency with SSH and the
process API.

A tooling-only alternative also exists (resolve the language-server
workspace via a `WORKSPACE` env value in `.mcp.json`). The agent-side
fix was preferred because it corrects the root cause for every stdio MCP
server, not just the two language servers, and keeps `.mcp.json`
portable.

Deferred (not in this PR): converting `NewManager` to an options struct
to avoid positional `nil` churn, and setting `PWD` alongside `cmd.Dir`.

</details>

---

Generated by Coder Agents on behalf of @jeremyruppel.

---------

Co-authored-by: Coder Agents <agents@coder.com>
2026-09-10 10:49:00 -04:00

56 lines
1.5 KiB
Go

package agentmcp
import (
"bytes"
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
"github.com/stretchr/testify/require"
"cdr.dev/slog/v3/sloggers/slogtest"
"github.com/coder/coder/v2/agent/agentexec"
"github.com/coder/coder/v2/codersdk/workspacesdk"
"github.com/coder/coder/v2/testutil"
)
// TestHandleCallTool_ErrorMapping verifies the call-tool handler maps
// Manager errors to the right HTTP status codes. Tool discovery is no
// longer served over HTTP (the agentcontext manager reads the catalog
// in-process), so only the execution endpoint is exercised here.
func TestHandleCallTool_ErrorMapping(t *testing.T) {
t.Parallel()
ctx := testutil.Context(t, testutil.WaitShort)
logger := slogtest.Make(t, nil)
m := NewManager(ctx, logger, agentexec.DefaultExecer, nil, nil, nil, nil)
t.Cleanup(func() { _ = m.Close() })
api := NewAPI(m)
cases := []struct {
name string
toolName string
wantCode int
}{
{name: "InvalidToolName", toolName: "noseparator", wantCode: http.StatusBadRequest},
{name: "UnknownServer", toolName: "ghost__echo", wantCode: http.StatusNotFound},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
t.Parallel()
body, err := json.Marshal(workspacesdk.CallMCPToolRequest{ToolName: tc.toolName})
require.NoError(t, err)
req := httptest.NewRequest(http.MethodPost, "/call-tool", bytes.NewReader(body))
req.Header.Set("Content-Type", "application/json")
rec := httptest.NewRecorder()
api.Routes().ServeHTTP(rec, req)
require.Equal(t, tc.wantCode, rec.Code)
})
}
}