Skip to content

Add a bounded outbound MCP read client - #1194

Open
zlareb1 wants to merge 18 commits into
mainfrom
feat/mcp-document-sources
Open

zlareb1 wants to merge 18 commits into
mainfrom
feat/mcp-document-sources

Conversation

@zlareb1

@zlareb1 zlareb1 commented Nov 22, 2026 •

Copy link
Copy Markdown
Member

Related: #1189
Related: #1190
Related: #1068

Changelog category (leave one):

  • Improvement

Changelog entry

Add the internal read client for configured remote MCP document sources. Resource reads and explicitly mapped read tools share bounded transport, schema checks and normalized evidence.

Why

A shared outbound client lets source integration configure a protocol endpoint and approved reads rather than add another API connector. Protocol compatibility does not establish permission, complete enumeration or synchronization support.

This PR covers the internal outbound client. Loom continues to expose document, source, memory and code operations through one existing inbound MCP endpoint and operation registry. The companion worker integration owns outbound requests and credentials. This PR does not add another inbound server, register document operations, or wire core to upstream services.

Scope and risk

The official maintained protocol SDK supplies remote Streamable HTTP. Configuration pins an HTTPS endpoint, credential origin/audience, approved tool names and schemas, fixed scope arguments and selected resource identities. Listing/search produce candidates; discovery snippets cannot substitute for a successful selected read. Descriptions and read-only hints grant no authority.

The transport reuses vetted DNS, preserves the approved Host/TLS identity, refuses redirects and environment proxies, bounds requests/results/pages/bytes/time, and rechecks current caller authority. A read receipt identifies the requested resource and hashes the returned text and validated client configuration. The caller authorizes the connection separately. Citation links are never fetched. Errors expose bounded codes under existing private-work handling. The integrating source layer remains responsible for owner/tenant binding, protected publication, accounting and storage.

Discovery-only sessions close without treating a queued initialization notification as a foreground request. Closing transport background dispatch is cancelled only for the normal closed-state condition. Foreground closed-session calls and observed authorization/protocol failures remain terminal. No extra flush RPC, sleep or private SDK patch is used.

Supported content is text resources and explicitly mapped structured tool output under the documented schema subset. Binary resources, unstructured-only tools, interactive authorization/refresh, local commands and legacy transports are unsupported. Synthetic servers establish no external-service qualification. Partial pages, errors and notifications prove neither deletion nor ACL completeness. Live work imports nothing.

The maintenance SDK line avoids automatic upstream-error telemetry without a public per-client suppression facility. There is one SDK path, with no tracer patch or version fallback. The architecture page records these boundaries.

Compatibility, rollout and rollback

  • Wire/settings: no operation, request field, source kind or default changes; no ignored_args change.
  • Storage: no table, migration, account, credential, checkpoint, document or original changes. Adjacent builds use the existing schema.
  • Operator steps: none. No source/runtime configuration changes.
  • Rollback removes the client and dependency additions without a data migration.

The replacement still requires an old-build refusal and owner-led reconfiguration contract. A source kind alone is not rolling-upgrade proof. No existing credential is sent to an inferred endpoint.

Tests

The four focused client, cancellation, protocol, and network test files pass 299 cases with MCP SDK 1.30.0. The tests cover catalog changes during pagination, boolean and numeric schema pins, missing tool capabilities, and invalid read selectors. They also cover receipt size validation before connection, preservation of a denial through cancellation, deadline failure during pool cleanup, and rejection of HTTP 202 for a read request. Additional regressions cover exact native URI spelling, refusal of URI credentials, valid hostless resources, a required search selector, a catalog change during final authorization, refusal before dispatch when the tool catalog changes during transport authorization, and refusal of HTTP 200 or a nonempty HTTP 202 for notifications. Ruff, strict mypy for the client, and the repository function-length gate pass.

python -m pytest -q tests/unit/test_mcp_source_client.py tests/unit/test_mcp_source_cancellation.py tests/unit/test_mcp_source_protocol.py tests/unit/test_mcp_source_network.py

Hosted CI and fresh review on the candidate commit are pending. These tests use synthetic sources.

AI assistance in the code

  • AI-generated: Codex wrote most of the diff. Independent source review and exact-head hosted results are reported before merge.

  • I can explain the change and its integration boundaries.

Checklist

  • All required exact-head hosted checks pass and fresh review has no findings.
  • Applicable generated documentation is regenerated through its generator.
  • No migration, source-row, dashboard or plugin-shipped change.
  • Architecture names unsupported profiles and the publication/storage boundary.
  • No runtime configuration or stored data changed.
  • Commits are signed off.

Note

Medium Risk
New outbound HTTP client with credential handling and DNS pinning increases attack-surface complexity, but it is internal-only, fail-closed, and not yet on the production source path.

Overview
Adds an internal outbound MCP read client (server/clients/mcp_source.py) for pulling text from a single pinned HTTPS Streamable HTTP endpoint, plus architecture documentation and mcp / jsonschema dependencies.

The client is config-driven: one endpoint, optional bearer token with audience binding, approved resource IDs for reads, and up to two explicitly mapped tools for search/read. It uses the official MCP SDK behind a custom pinned transport (pinned_target, no redirects/proxy env, allowlisted headers, wire/size/time limits) and a caller-supplied validate_access hook at every operation. Discovery, listing, search, and read return normalized evidence and read receipts (content + config hashes); errors surface only fixed codes under private_work.

Tests add broad unit coverage (mock SDK servers, cancellation/drain behavior, TLS/SSE against a local FastMCP server). No wire/API, storage, or source-registration integration in this PR—the client is a prerequisite for later source-layer wiring.

Reviewed by Cursor Bugbot for commit 85725f0. Bugbot is set up for automated code reviews on this repo. Configure here.

@vercel

vercel Bot commented Nov 22, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated
loom-docs Ready Ready Preview Nov 28, 2026 8:57am UTC
loom-telemetry Ready Ready Preview Nov 28, 2026 8:57am UTC

Request Review

@zlareb1
zlareb1 force-pushed the feat/mcp-document-sources branch 5 times, most recently from 865c09c to 6ec5008 Compare November 22, 2026 23:02

@zlareb1 zlareb1 left a comment •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Removed.

@zlareb1
zlareb1 force-pushed the feat/mcp-document-sources branch from 557f498 to d758d10 Compare November 23, 2026 00:24

@zlareb1 zlareb1 left a comment •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Removed.

@zlareb1 zlareb1 left a comment •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Removed.

@zlareb1
zlareb1 force-pushed the feat/mcp-document-sources branch from ec9adb7 to 45e93d7 Compare November 23, 2026 01:59

@zlareb1 zlareb1 left a comment •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Removed.

@zlareb1
zlareb1 force-pushed the feat/mcp-document-sources branch from 45e93d7 to d62160b Compare November 23, 2026 02:25

@zlareb1 zlareb1 left a comment •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Removed.

@zlareb1 zlareb1 left a comment •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Removed.

Configure one remote read engine for resources and explicitly approved tools. Keep protocol evidence separate from source authorization and publication, and qualify transport limits, revocation and cancellation with synthetic SDK servers.

Signed-off-by: zlareb1 <lareb.zafar@clickhouse.com>
A cancelled response waiter leaves the SDK HTTP task alive. Give each open client a lifecycle owner, join its shutdown before returning cancellation, and retain the session deadline through idle time. Verify stream cleanup, repeated cancellation and isolation from other clients.

Signed-off-by: zlareb1 <lareb.zafar@clickhouse.com>
Join the SDK lifecycle owner after every operation failure, including request
deadlines and cancellation after a background refusal. Preserve the first
caller cancellation while draining stream finalizers and the HTTP pool.

Signed-off-by: zlareb1 <lareb.zafar@clickhouse.com>
Reject schema keywords outside their declared type and validate with an
explicit registry that cannot retrieve external resources. Retain response
cleanup through authority checks and join its finalizer outside the work
deadline when handoff fails or is cancelled.

Signed-off-by: zlareb1 <lareb.zafar@clickhouse.com>
Check session state and total expiry around authority callbacks and publication
so background HTTP failures cannot yield successful read evidence. Scope issued
cursors by operation and query and accept an absent optional final-page cursor.

Signed-off-by: zlareb1 <lareb.zafar@clickhouse.com>
Record HTTP status and media failures before the SDK can consume background
errors. Preserve optional GET and DELETE responses with status 405. Distinguish
omitted mapped cursors from present invalid values during page normalization.

Signed-off-by: zlareb1 <lareb.zafar@clickhouse.com>
Use the HTTP client normalization for audience and endpoint checks and refuse pin helpers that change the authorized Host or TLS name.

Signed-off-by: zlareb1 <lareb.zafar@clickhouse.com>
Keep foreground closed-session calls terminal while joining pending SDK notification work. Cover discovery-only resource and action-only servers without extra RPCs.

Signed-off-by: zlareb1 <lareb.zafar@clickhouse.com>
A session deadline can start closing the SDK and HTTP pool before a caller exits or tries another read. Joining the existing teardown keeps that caller from cancelling the pool finalizer and losing the timeout.

Signed-off-by: zlareb1 <lareb.zafar@clickhouse.com>
@zlareb1

zlareb1 commented Nov 25, 2026

Copy link
Copy Markdown
Member Author

The pool cleanup fix is at b1371b71b4948c93a2d8d20da0e7dc4b5ea02890. Both new regressions failed against 655ac4fa1ca1643e9a586b04317a4e276fb10bd1: an expired session could return from a late read or context exit while its HTTP pool was still closing. Both paths now wait for the pool close and report the deadline. The socket-free client, cancellation and protocol set passes 268 cases. Focused Ruff lint and formatting checks pass.

The previous hosted run concluded with failed unit shard 4 and Postgres 18 storage jobs. Those results remain failures tied to the previous head. Fresh whole-source review and required hosted checks are pending for this commit.

A live event stream can hold the connection needed for session termination. The owner joins SDK dispatch before DELETE and keeps private response-finalizer failures behind fixed error codes. Merge current main and regenerate the dependency lock to restore hosted checks.

Signed-off-by: zlareb1 <lareb.zafar@clickhouse.com>
@zlareb1

zlareb1 commented Nov 25, 2026

Copy link
Copy Markdown
Member Author

At 514c3f7a84a58e2c27df942a578218c114035cc0, background SDK requests drain before session DELETE. Finalizer errors return fixed codes without upstream error text. A caller that arrives during teardown waits for the HTTP pool to finish closing. The deadline regressions reproduced both premature exit paths, and separate cases reproduced the stream finalizer and outstanding GET failures. The combined socket-free client suite passed 273 cases.

The preceding head conflicted with main and did not start required CI. This head merges main forward without rewriting history and regenerates the lock with MCP 1.30.0. Fresh whole-source review and exact-head hosted checks are pending.

@zlareb1

zlareb1 commented Nov 25, 2026

Copy link
Copy Markdown
Member Author

Independent source review of b1371b71b4948c93a2d8d20da0e7dc4b5ea02890 covered all nine paths. Both held-pool deadline regressions passed. Five other cases reproduced:

  • A tools/list_changed notification between pages can leave a stale approved tool list usable.
  • Schema equality can treat boolean false and numeric 0 as the same const.
  • A mapped read can call tools without the negotiated tools capability.
  • A mapped read without a text selector can issue a receipt for an empty body it never selected.
  • A pool-finalizer error can replace an idle session timeout.

This review is tied to the superseded commit. The cases are being checked against the current commit before the next fix. An independent review of the current commit and the required CI run are separate; its mypy-gate step has reported failure.

The SDK types the negotiated version as a string or integer. Session termination sends that value in an HTTP header, which accepts text.

Signed-off-by: zlareb1 <lareb.zafar@clickhouse.com>
A catalog change invalidates discovery, and a rejected read keeps its original failure through session cleanup. Validate tool mappings before opening a session so the read receipt can identify the approved configuration.

Signed-off-by: zlareb1 <lareb.zafar@clickhouse.com>

@cursor cursor 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.

Stale Bugbot comment from a previous run.

Comment thread server/clients/mcp_source.py Resolved
Comment thread server/clients/mcp_source.py Resolved
Comment thread server/clients/mcp_source.py Resolved
Signed-off-by: zlareb1 <lareb.zafar@clickhouse.com>
Signed-off-by: zlareb1 <lareb.zafar@clickhouse.com>
Signed-off-by: zlareb1 <lareb.zafar@clickhouse.com>
@zlareb1

zlareb1 commented Nov 26, 2026

Copy link
Copy Markdown
Member Author

Independent agent review approved 867da43730f8c53e71408552c5112752060e3e54 with no findings. Ten focused tests passed independently. They verified that invalid notification acknowledgments stop resource reads, catalog changes stop stale dispatch or receipt delivery, and native resource identifiers keep their exact spelling while refusing URI credentials. The complete local focused suite passed 299 tests. This is the agent review result; GitHub review and hosted checks are separate gates.

…rces

Signed-off-by: zlareb1 <lareb.zafar@clickhouse.com>
@zlareb1

zlareb1 commented Nov 26, 2026

Copy link
Copy Markdown
Member Author

Refreshed this PR on the current main. The client, tests and dependency lock are unchanged. The documentation index matches its generator on the new base.

The focused client, cancellation, protocol and network tests passed, along with Ruff, the function length gate, strict type checking and offline lock verification. Fresh independent review and hosted checks are running on this head.

@zlareb1

zlareb1 commented Nov 26, 2026

Copy link
Copy Markdown
Member Author

Fresh independent review approved e7f6b7e43e with no findings. The review checked constructor validation, the last authorization check before dispatch, refusal of unexpected notification acknowledgments, and transport cleanup order. The guarded focused run passed all 299 client, network, cancellation and protocol tests on this head. Hosted checks and repository approvals are still pending.

@zlareb1

zlareb1 commented Nov 26, 2026

Copy link
Copy Markdown
Member Author

The integration shard on e7f6b7e43e67e3e6c1e9ee3adf51a42fce36c7bb failed in test_real_person_queries_report_their_physical_work. ClickHouse timed out flushing system.trace_log. The test calls SYSTEM FLUSH LOGS, but its assertions read only system.query_log. The same shard passed on the base commit. The MCP client does not change this test or its code path.

Job: https://github.com/ClickHouse/loom/actions/runs/45873973784/job/140096349424
Base control: https://github.com/ClickHouse/loom/actions/runs/45873072673/job/140093281512

#1495 scopes the separate Postgres batching test to the query log. The SCIM fixture needs the same targeted flush and a passing hosted run. Its physical-work assertions should stay intact.

@zlareb1

zlareb1 commented Nov 26, 2026

Copy link
Copy Markdown
Member Author

#1495 now changes test_real_person_queries_report_their_physical_work to flush only query_log. It leaves the query count and reads assertions intact. This is the same test that failed on e7f6b7e; the earlier revision of #1495 changed only the Postgres batching test. The repair is still in review and CI. Once it lands, this PR can bring in the fix and run the integration shard on the resulting head.

The SDK can report a protocol error and continue to deliver messages. Record the error in the session failure state so a later result cannot produce a read receipt.

Signed-off-by: zlareb1 <lareb.zafar@clickhouse.com>
Regenerate the documentation index from both sets of pages.

Signed-off-by: zlareb1 <lareb.zafar@clickhouse.com>

@cursor cursor 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.

Cursor Bugbot has reviewed your changes using high effort and found 1 potential issue.

Fix All in Cursor

❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, have a team admin enable autofix in the Cursor dashboard.

Reviewed by Cursor Bugbot for commit 85725f0. Configure here.

if not isinstance(path, tuple) or len(path) > 8:
raise MCPSourceError("config")
for part in path:
_string(part, 128)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Cursor mappings accepted that cannot paginate

Medium Severity

Construction already rejects incomplete search and read selectors, but it still accepts a mapping with next_cursor_path and no cursor_argument, or a cursor_argument that is not a writable input-schema property. The first page can succeed and return next_cursor; using that cursor then raises and the session is closed.

Additional Locations (2)
Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 85725f0. Configure here.

This branch has not been deployed

No deployments
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.

1 participant