Skip to content

mcp: inbound MCP server mode — serve memory_search / kb_search / SCARS live - #218

Merged
FMXExpress merged 2 commits into
mainfrom
claude/mcp-server-mode
Jun 10, 2026
Merged

FMXExpress merged 2 commits into
mainfrom
claude/mcp-server-mode

Conversation

@FMXExpress

Copy link
Copy Markdown
Owner

Summary

External MCP runtimes (Claude Desktop, Cursor, Codex CLI, anything that speaks MCP) can now consume PasClaw's memory_search, kb_search, session_search, and SCARS (workspace/memory/SCARS.md is reachable through memory_search) live against the same corpus the local CLI sees. Completes the source-of-truth story the static export commands started — no more drifting copies for "atlas" / "hermes"-style consumers.

Three transport surfaces, one core

  • POST /mcp on the existing gateway listener — alongside /v1/* on the same port, no extra daemon. Uses the MCP Streamable HTTP transport's plain-JSON response shape.
  • Dedicated --mcp-port — pasclaw serve --mcp-port 8089 (and pasclaw gateway --mcp-port 8089) spins up a second TGatewayServer in MCP-only mode, so a heavy /v1/responses streaming load can't compete with MCP requests for Indy worker threads. Both listeners share one TToolRegistry — same answers.
  • pasclaw mcp stdio — newline-delimited JSON-RPC on stdin/stdout for hosts (Claude Desktop config, Cursor, Codex CLI) that spawn MCP servers as subprocesses. Banner is suppressed on stdio so JSON-RPC parsers never see a stray UTF-8 box-drawing character.

Safety posture

  • Read-only by default. TMCPServerCore filters to tcReadOnly tools (memory_search / memory_get / kb_search / kb_get / session_search). A foreign MCP host calling fs_write or shell on the operator's box is exactly the bad outcome sandbox exists for.
  • --mcp-allow-write opts in to mutating tools when the operator actually wants the full surface.
  • Per-name allowlist (SetMCPAllowList) lets callers narrow exposure further.
  • Tool failures → MCP isError content blocks (not transport errors), so hosts keep the session alive when e.g. the memory index goes temporarily offline.

MCP protocol surface implemented

initialize · notifications/initialized · ping · tools/list · tools/call.

resources/* and prompts/* are deliberately unimplemented in v1; a future revision can map skills to MCP prompts (a better semantic fit than as tools, since a skill on its own without the parent LLM isn't directly callable).

Files

  • New: src/pkg/mcp/PasClaw.MCP.Server.pas (transport-agnostic core, ~370 lines)
  • New: src/tests/mcp_server_tests.pas (12 cases covering protocol shapes + mutating gate + allowlist + id type round-trip + parse error + isError + ping)
  • Wired: src/pkg/gateway/PasClaw.Gateway.Server.pas (route + MCP-only mode + per-instance policy)
  • Wired: src/cmd/PasClaw.Cmd.Serve.pas + src/cmd/PasClaw.Cmd.Gateway.pas (CLI flags + dual-listener spawn)
  • Wired: src/cmd/PasClaw.Cmd.MCP.pas (new stdio subverb)
  • src/pasclaw/PasClaw.dpr (suppress banner under mcp stdio)
  • src/pasclaw/PasClaw.dproj (DCCReference for new unit)
  • Makefile (new test-mcp-server target, added to umbrella test)

Test plan

  • make test — full suite green incl. new test-mcp-server
  • Live HTTP probe: pasclaw serve --port 18099 then curl POST /mcp for initialize / tools/list / tools/call fs_write (blocked) / /v1/health (still works alongside)
  • Stdio: printf '%s\n' '{...initialize...}' '{...tools/list...}' | pasclaw mcp stdio returns two clean JSON-RPC responses (no banner)
  • Delphi dcc64 build — needs your local toolchain

https://claude.ai/code/session_01TBcLtmpj7dqA5tyFbGnQon


Generated by Claude Code

…RS / sessions live

External MCP runtimes (Claude Desktop, Cursor, Codex CLI, and anything else
that speaks the protocol) can now consume PasClaw's memory_search, kb_search
(knowledgebase), session_search, and SCARS (workspace/memory/SCARS.md is
reachable through memory_search) live against the SAME corpus the local CLI
sees. Completes the "source of truth" story the static export commands
started -- no more drifting copies.

Three transport surfaces, one core:

  1. POST /mcp on the existing gateway listener -- alongside /v1/*, no
     extra daemon to babysit. The MCP route uses the MCP Streamable HTTP
     transport's plain-JSON response shape (no SSE in v1; server-pushed
     notifications are a follow-up).
  2. POST /mcp on a dedicated port via `pasclaw serve --mcp-port 8089` /
     `pasclaw gateway --mcp-port 8089` -- spins up a second TGatewayServer
     in MCP-only mode (all other routes 404) so a heavy /v1/responses
     streaming load can't compete with MCP requests for Indy worker
     threads. Both listeners share the same TToolRegistry instance, so
     they see identical results.
  3. `pasclaw mcp stdio` for hosts that spawn MCP servers as subprocesses
     (Claude Desktop config, Cursor's MCP settings, Codex CLI). Newline-
     delimited JSON-RPC on stdin/stdout, matching the framing
     PasClaw.MCP.StdioClient already uses for outbound MCP.

Safety posture:

  - Read-only by default. The TMCPServerCore filters to tcReadOnly tools
    (memory_search / memory_get / kb_search / kb_get / session_search and
    any other read-only tool in the registry). A foreign MCP host calling
    fs_write or shell on the operator's box is exactly the bad outcome
    sandbox exists for.
  - `--mcp-allow-write` opts in to mutating tools when the operator
    actually wants the full surface (e.g. dev-time integration with a
    trusted local host).
  - SetMCPAllowList lets callers narrow exposure further -- empty array
    means "anything that passes the mutating gate", non-empty means
    "only these names".
  - Tool failures land as MCP isError content (not transport errors) so
    hosts keep the session alive when e.g. the memory index goes
    temporarily offline.
  - Banner suppressed on `pasclaw mcp stdio` so the host's JSON-RPC
    parser never sees a stray UTF-8 box-drawing character on first read.

Implements:
  - initialize / notifications/initialized / ping / tools/list / tools/call

New unit: src/pkg/mcp/PasClaw.MCP.Server.pas (transport-agnostic core).
Wired into both Cmd.Serve and Cmd.Gateway. Stdio variant lives at
`pasclaw mcp stdio`.

Tests: src/tests/mcp_server_tests.pas covers initialize / notification /
tools-list filtering / tools-call dispatch / isError handling / mutating
gate / unknown tool / unknown method / parse error / allowlist / ping
round-trip / id type round-trip.

https://claude.ai/code/session_01TBcLtmpj7dqA5tyFbGnQon

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 612aa9a904

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread src/pkg/mcp/PasClaw.MCP.Server.pas Resolved
…on PR #218)

Codex finding: the substring-based id extractor scanned the raw request
line for the first "id" occurrence. JSON object member order isn't fixed,
so a perfectly valid request like

  {"method":"tools/call","params":{"arguments":{"id":"doc1"}},"id":5}

would echo back "id":"doc1" instead of "id":5, breaking request/response
correlation when the host's tool arguments happen to include an "id" field
(common: document ids, session ids, anything).

Fix: look up "id" on the parsed TJsonObject. Detect type via a JSON-
illegal sentinel default on GetStr (control-char triplet, can never
appear in a valid JSON string), so a string id round-trips as a string
and a numeric id round-trips as a number. Escape string ids via
JsonEscape before quoting on the way back out.

New test (TestIdNestedInParamsDoesNotConfuseEcho) pins the contract:
nested params.arguments.id never leaks into the response echo, even when
it appears before the top-level id in the request body.

https://claude.ai/code/session_01TBcLtmpj7dqA5tyFbGnQon
@FMXExpress
FMXExpress merged commit eb65f99 into main Jun 10, 2026
FMXExpress pushed a commit that referenced this pull request Jun 13, 2026
Both changelog files were stuck at the 2026-06-10 TUI / background-
subagent / session_search / tool-RPC entries. ~7 weeks of merged
PRs (#214 through #244) had landed without a corresponding entry in
either file -- the git log was the only record of features like the
knowledgebase, inbound MCP server mode, checkpoints + /undo,
heartbeat daemon, shell backends (local | docker), send_message,
promptware defense, Windows shell-output encoding fixes, fs_grep
ripgrep optimisations, OpenTelemetry traces, and `pasclaw agent
--quiet`.

Added (newest first):

  2026-06-13
    #244  agent --quiet log-level clamp

  2026-06-12
    #243  dcc64 search path + agent --quiet / -q
    #242  OpenTelemetry traces (OTLP/HTTP+JSON)
    #241  fs_grep tier 5+6 (byte walker + Boyer-Moore-Horspool)
    #240  fs_grep tier 1-4 (deferred hash + skip-dirs + binary
          sniff + size cap)

  2026-06-11
    #239  Windows shell output: auto-detect UTF-8 vs OEM
    #238  Hashline fs_read header mojibake fix (¶ vs ¶)
    #237  Windows shell output: OEM codepage decode

  2026-06-10
    #233  Shell backends (local | docker via IShellBackend)
    #232  Heartbeat daemon + reversible condensation (CCR)
    #230  send_message tool + condenser families + promptware
          defense + task-aware MEMORY.md slicing

  2026-06-09
    #223  /goal Ralph loop + judge model + JSON-aware condenser
    #222  /undo wired into agent + sample dprojs
    #221  Checkpoints (auto-snapshot + TUI /undo)
    #220  mcp catalog: lenient hub projector
    #219  mcp: SSE / Streamable HTTP / stdio hub transports
    #218  Inbound MCP server mode
    #217  onboard: offer to index docs into the knowledgebase
    #214  Knowledgebase (RAG over operator-curated docs)

Skipped from this changelog (build-system / Delphi-fix / FPC-fix
PRs visible in the git log but not user-facing features):
#215, #216, #224, #225, #226, #227, #228, #229, #231, #234, #236.

Both files (README.md and docs/changelog.md) updated with the same
entries -- intentional mirror so a reader on either surface sees
the same history. Same prose in both; same footnote refs at the
bottom.

Validated: every [#N] reference in both files has a matching [#N]:
URL footnote (no broken links).
FMXExpress pushed a commit that referenced this pull request Jun 13, 2026
Codex review on PR #245 caught five inline issues -- all real, all
documentation referencing CLI flags / subcommands / URL routes that
don't exist in the code:

1. docs/mcp.md documented `--mcp-allow <list>`, `--mcp-read-only`,
   `--mcp-only` for the inbound MCP server. None of those exist.
   The actual flags from src/cmd/PasClaw.Cmd.Gateway.pas:
     - `--mcp-port <p>` spawns the second MCP-only listener (the
       inbound-MCP server is read-only by default; this flag is what
       wakes the isolation pattern).
     - `--mcp-allow-write` flips that listener from read-only to
       allowing mutating tools.
   No comma-separated per-tool allowlist; no standalone --mcp-only.

2. docs/commands.md, docs/configuration.md, docs/providers.md
   referenced `pasclaw auth fallback openai gemini`. src/cmd/
   PasClaw.Cmd.Auth.pas only dispatches `status` / `login` / `logout`
   / `weixin` -- no `fallback` subcommand exists. The fallback chain
   is configured by editing `fallbacks[]` in config.json directly.

3. docs/channels.md + docs/commands.md + docs/gateway.md documented
   `pasclaw gateway --discord --token <BOT_TOKEN>` and
   `pasclaw gateway --slack`. Those flags don't exist in the gateway
   ArgParser -- the channel units (PasClaw.Channels.Discord with
   TDiscordBot, PasClaw.Channels.Slack with the Events API receiver)
   exist but aren't wired to a CLI flag yet. Currently outbound-only
   via `pasclaw post discord/slack` and the `send_message` tool.

4. docs/channels.md said "Point LINE's webhook URL at
   https://<gateway>/v1/line/webhook". src/pkg/channels/
   PasClaw.Channels.LINE.pas line 13 says POST /webhooks/line.

5. docs/channels.md said "Point Meta's webhook URL at
   https://<gateway>/v1/whatsapp/webhook". src/pkg/channels/
   PasClaw.Channels.WhatsApp.pas lines 18+25 say GET/POST
   /webhooks/whatsapp.

All five are docs-only bugs -- the code is fine. Without the fix
operators following the docs would silently fail: --mcp-allow gets
ignored as an unknown flag, --discord/--slack same, the webhook URLs
404 at the gateway and Meta/LINE rejects the subscribe handshake.

Fixes:
- docs/mcp.md: replaced the wrong flag block with the real
  `--mcp-port` / `--mcp-allow-write` shape, plus a paragraph
  explaining the read-only-by-default contract.
- docs/commands.md + docs/configuration.md + docs/providers.md:
  removed `auth fallback`; replaced with "edit fallbacks[] in
  config.json directly".
- docs/channels.md: moved Discord and Slack from the bidirectional
  table into outbound-only, added inline notes about the
  not-yet-wired inbound paths. Fixed both webhook URLs.
- docs/commands.md + docs/gateway.md: dropped --discord/--slack
  from the gateway running examples, added --mcp-port to the same
  example block since it's a real isolation flag.
- docs/troubleshooting.md: --mcp-only -> "the listener spawned by
  --mcp-port <p>" so the troubleshooting entry maps to a real flag.
- docs/changelog.md + README.md: rewrote the PR #218 changelog
  entry to describe the real flags (--mcp-allow-write defaulting
  to read-only, --mcp-port for the second listener).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants