Skip to content

server: location reload invalidates the caller's held layer, so its tool catalog is empty #59993

Open

Description

@GladSI

Summary

POST /api/location/reload is the only in-place way to reload a location (used to pick up a rebuilt
MCP server without restarting the daemon). It invalidates every loaded location and boots the
replacements, so the server side is ready when the call returns — but the step that performed the
reload still holds the invalidated build, and its tool catalog is empty until the next request
re-resolves the location. Any tool call made in that window fails as Unknown tool '<server>.<name>',
which is indistinguishable from an MCP server that is not connected.

Environment

  • opencode version: v2.2.0 (local clone, fa1260d6ca)
  • OS: Linux 7.0.0-42-generic (x64)
  • Terminal: TERM=xterm-256color, COLORTERM=truecolor (kitty)
  • Shell: /bin/bash
  • Install/channel: local dev checkout (~/repos/opencode), opencode serve daemon shared by sessions
  • Active plugins: none

Reproduction

  1. Start the daemon (opencode), open a session in a project with a local MCP server
    (.opencode/opencode.json → mcp["llm-pipeline"]).
  2. Confirm the server's tools are callable in that session.
  3. From a tool call in the same session, POST http://127.0.0.1:<port>/api/location/reload
    (basic auth from ~/.local/state/opencode/service.json).
  4. Immediately make another MCP tool call from the same session.

Expected Behavior

Either the reload keeps the previous build alive for consumers that still hold it, or the caller's
next tool call re-resolves the location transparently. The model should never see a tool it had a
second ago as "unknown".

Actual Behavior

The next call fails with Unknown tool 'llm-pipeline.check_mcp' (and the session's tool list shows
only the non-MCP tools). The retry of the same call — i.e. the request after the next one —
answers normally, against the NEW revision. Measured three times (2026-10-22 ×2, 2026-10-28) on
2.0.32 and 2.2.0-shaped builds; the daemon pid never changes.

Additional Context

Localisation (read-only, no patch attempted):

  • packages/server/src/handlers/location.ts → location.reload → LocationServiceMap.reload()
    (packages/core/src/location-service-map.ts), which invalidates each location's layer and
    re-boots the replacement, waiting for the builds. So the server is ready on return.
  • packages/server/src/location.ts resolves location services per REQUEST, which is why the request
    after the reload sees the new instance — and why the request that performed the reload does not.
  • The tool registry is not the culprit: packages/core/src/tool/mcp.ts reconciles from the
    McpEvent.ToolsChanged bus event with a 100 ms debounce, and
    packages/core/src/mcp/index.ts (connect) publishes that event after
    stopServer + startServer under the per-server lock.

Suggestion: a per-server restart already exists as
POST /api/experimental/mcp/:server/connect and does not touch the location at all — that is the
endpoint a caller who only needs a fresh MCP server should use, and it is what we now use. If the
intent of location.reload is to serve holders of the old build as well, keeping the previous build
alive until its refs drain (or retrying internally inside the session) would remove this window.

Impact: an agent that refreshes its MCP server between steps loses the tool channel for one turn and
tends to conclude the server is down; the documented remedy had to become "retry the same call once",
which is a property of this API rather than of the caller.

Activity

  1. opencodejr commented on Oct 28, 2026

    @opencodejr
    Contributor

    Thanks for the detailed report. I can reproduce this on 2.2.0, and it still happens on the latest dev (a882cf98a0).

    Setup: a minimal local stdio MCP server, set to codemode: false so its tool shows up as a plain tool named pipe_check, and a simulated model. In one turn:

    1. pipe_check works.
    2. A shell tool call is in progress while POST /api/location/reload runs, and the reload returns successfully.
    3. The next model request in the same turn no longer lists pipe_check. Calling it returns No tool named "pipe_check" is currently available.

    In my run, the tool stayed missing for the rest of that turn, not just the next call. The next user prompt got the tool back, served by a new MCP server process.

    The recording and script below show the whole sequence. As you noted, restarting just the server with POST /api/experimental/mcp/:server/connect avoids this.

    recording.mp4
    Reproduction script (drive.ts)
    // Repro for #59993: POST /api/location/reload during a turn removes the MCP tools
    // from the rest of that turn (the step that triggered the reload holds the invalidated build).
    import { Effect, Stream } from "effect"
    import { Llm, OpenCodeDriver } from "opencode-drive"
    
    // Minimal stdio MCP server exposing one tool, `check`.
    const mcpServer = `
    import readline from "node:readline"
    const rl = readline.createInterface({ input: process.stdin })
    const send = (m) => process.stdout.write(JSON.stringify(m) + "\\n")
    rl.on("line", (line) => {
      let msg; try { msg = JSON.parse(line) } catch { return }
      if (msg.id === undefined) return
      if (msg.method === "initialize")
        return send({ jsonrpc: "2.0", id: msg.id, result: { protocolVersion: msg.params?.protocolVersion ?? "2025-06-18", capabilities: { tools: {} }, serverInfo: { name: "pipe", version: "1.0.0" } } })
      if (msg.method === "tools/list")
        return send({ jsonrpc: "2.0", id: msg.id, result: { tools: [{ name: "check", description: "Health check", inputSchema: { type: "object", properties: {} } }] } })
      if (msg.method === "tools/call")
        return send({ jsonrpc: "2.0", id: msg.id, result: { content: [{ type: "text", text: "pipe ok pid=" + process.pid }] } })
      send({ jsonrpc: "2.0", id: msg.id, result: {} })
    })
    `
    
    const toolNames = (body: any): string[] =>
      (body?.tools ?? []).map((t: any) => t.name ?? t.function?.name).filter(Boolean)
    const log = (line: string) => console.log("[repro]", line)
    const lastToolResult = (body: any) => {
      const s = JSON.stringify(body?.messages ?? body?.input ?? body)
      const results = [...s.matchAll(/pipe ok pid=\d+|No tool named[^.]*\.|Unknown tool[^"\\]*/g)].map((m) => m[0].replace(/\\+"/g, "'"))
      return results.length ? results[results.length - 1] : "(no MCP result)"
    }
    
    export default OpenCodeDriver.use(
      {
        ...(process.env.OC_DEV ? { opencode: { dev: process.env.OC_DEV } } : {}),
        project: { git: true, files: { "mcp-server.mjs": mcpServer } },
        config: { mcp: { pipe: { type: "local", command: ["node", "mcp-server.mjs"], codemode: false } } },
        tools: ["shell"],
        tui: { recording: true },
      },
      ({ ui, llm, tools, opencode }) =>
        Effect.gen(function* () {
          const shells = yield* tools.control("shell")
          let step = 0
          yield* llm.serve((request) => {
            const names = toolNames(request.body)
            if (names.length === 0) return Stream.make(Llm.text("Title"))
            step++
            log(`step ${step}: pipe_check offered=${names.includes("pipe_check")}; last MCP result: ${lastToolResult(request.body)}`)
            switch (step) {
              case 1: // turn 1: MCP works
                return Stream.make(Llm.toolCall({ index: 0, id: "call_mcp1", name: "pipe_check", input: {} }), Llm.finish("tool-calls"))
              case 2: // turn 1: a tool call performs the reload
                return Stream.make(Llm.toolCall({ index: 0, id: "call_reload", name: "shell", input: { command: "curl -X POST $URL/api/location/reload", description: "reload location" } }), Llm.finish("tool-calls"))
              case 3: // turn 1: MCP call right after the reload
                return Stream.make(Llm.toolCall({ index: 0, id: "call_mcp2", name: "pipe_check", input: {} }), Llm.finish("tool-calls"))
              case 4:
                return Stream.make(Llm.text("turn one done"))
              case 5: // turn 2 (new prompt): MCP call
                return Stream.make(Llm.toolCall({ index: 0, id: "call_mcp3", name: "pipe_check", input: {} }), Llm.finish("tool-calls"))
              default:
                return Stream.make(Llm.text("turn two done"))
            }
          })
          yield* ui.submit("check the pipe, reload, check again")
          const shell = yield* shells.take("call_reload")
          yield* opencode.location.reload()
          log("location.reload returned")
          yield* shell.succeed({ output: "reloaded\n", exit: 0 })
          // Wait for turn one to finish (the TUI's ui.matches can stall after the reload, so poll the step counter).
          while (step < 4) yield* Effect.sleep(200)
          yield* Effect.sleep(1500)
          yield* ui.screenshot("after-turn-one")
          yield* ui.submit("check the pipe again")
          while (step < 6) yield* Effect.sleep(200)
          yield* Effect.sleep(1500)
          yield* ui.screenshot("after-turn-two")
        }),
    )

    Run it with opencode-drive: opencode-drive run ./drive.ts. It drives opencode from your PATH; set OC_DEV to the path of an OpenCode checkout to run that from source instead.

  2. GladSI commented on Oct 28, 2026

    @GladSI
    Author

    Correction from the reporter, measured after filing — the per-server suggestion is not sufficient, and the summary above overstates what it fixes.

    I tried POST /api/experimental/mcp/<server>/connect as the workaround instead of POST /api/location/reload: it is accepted, it replaces the server process (407255 -> 450487), and it does not invalidate the location. The first tool call after it still failed with Unknown tool 'llm-pipeline.<name>', and the next request saw the full catalog again — the same symptom, now 4/4 occurrences across both endpoints.

    So the empty-catalog window is not produced by LocationServiceMap.reload alone. The tool registry is rebuilt from the same McpEvent.ToolsChanged event either way (packages/core/src/tool/mcp.ts → tools.reload() in reconcile), and the step that issued the restart keeps the registry it had already resolved; only the next request re-resolves it. A per-server restart avoids tearing down the location, which is worth having, but it does not remove the window.

    What would still be worth looking at on your side: either keep the previous tool-registry snapshot usable until its holders release it (mirroring the "old build for existing consumers" idea), or make the reconcile update the registry in place instead of replacing what a running step holds.

    The retry-once rule on our side is now unconditional for both endpoints; the issue remains valid as a report of the window, with this comment as the corrected scope.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions