Skip to content

Add a bounded outbound MCP read client - #1194

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

zlareb1 wants to merge 32 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 with MCP SDK 1.30.0 (332 cases in the four focused files on the head, with strict mypy for the client). The tests cover the relaxed schema subset (optional size bounds and additionalProperties, default, a 2020-12 or draft-07 $schema; $ref and anyOf still refused, so tools generated from nested or optional Python models are unsupported), searches without a cursor mapping never claiming completeness, listings that stay partial after a respelled row on any page, including when a restarted listing takes over the partial listing's cursor, restarted listings that receive the cursors a server issued before, output validation off the event loop, a DELETE answered 404, construction-time refusal of mappings whose calls could never succeed (undeclared or invalid fixed arguments, unsent required inputs, a cursor argument without a cursor path, paginated reads, and selected resource URIs the SDK would respell), UTF-8 size limits for non-ASCII text, the caller's query tag surviving a client call, 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 security-sensitive outbound HTTPS/MCP path with credential binding and pinned DNS, but it is not yet wired into source registration or stored configuration—integration still owns authorization and publication.

Overview
Adds an internal outbound MCP source client (server/clients/mcp_source.py) for bounded reads against a single configured HTTPS Streamable HTTP endpoint, using the official MCP SDK with a custom pinned transport (pinned_target), caller-supplied bearer credentials, and repeated validate_access checks.

The client supports capability discovery, native resources/list and resources/read, and explicitly mapped search/read tools with a restricted JSON Schema subset, approved resource IDs, pagination/cursor rules, wire and content limits, and normalized read receipts (content and config fingerprints). It does not register sources, persist data, or widen scope from server metadata; errors surface as fixed MCPSourceError codes.

Dependencies add mcp, jsonschema, and referencing (plus types-jsonschema for dev). Documentation adds docs/architecture/mcp-source-client.md and indexes it in llms.txt. Tests add large unit suites for protocol behavior, TLS/SSE integration, and cancellation/lifecycle draining.

Reviewed by Cursor Bugbot for commit f6d5be2. 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 Dec 1, 2026 9:11pm UTC
loom-telemetry Ready Ready Preview Dec 1, 2026 9:11pm 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>
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.

Stale Bugbot comment from a previous run.

Comment thread server/clients/mcp_source.py Resolved
zlareb1 and others added 5 commits December 1, 2026 15:06
Signed-off-by: zlareb1 <lareb.zafar@clickhouse.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A mapping with a next-cursor path but no cursor argument, or a cursor
argument the input schema does not declare as a string, returned a first
page whose cursor could never be sent. Construction now refuses both.

Signed-off-by: zlareb1 <lareb.zafar@clickhouse.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A tool mapping's query or id argument must be a declared string property,
and a cursor argument may not be required, since the first page sends none.
A read mapping makes one call and keeps the whole response, so it refuses
cursor settings instead of silently returning the first page. The new
dependencies sit after the existing aligned comments.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: zlareb1 <lareb.zafar@clickhouse.com>
Size limits on tool results counted JSON-escaped bytes, so non-ASCII
documents were refused at a fraction of the configured limit; they now
count UTF-8 bytes like resource reads. A mapping's fixed arguments must
be declared and valid, its required inputs must all be sent, and a cursor
argument needs a cursor path; a selected resource URI the SDK would
respell is refused before any request. Non-string mapped text is a schema
error, the client no longer leaves its query tag on the caller's later
queries, and the lock keeps main's format revision.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: zlareb1 <lareb.zafar@clickhouse.com>
Tool schemas may omit size bounds and a closed additionalProperties, since
every value is capped by its byte budget, and may carry a 2020-12 or
draft-07 $schema annotation; references and combinators stay refused, so
tools generated from nested or optional Python models are unsupported. A
search without a cursor mapping no longer claims its page is the last, and
a listing leaves out resources whose URI the SDK would respell instead of
failing the session. A DELETE answered 404 closes cleanly, every
construction refusal is a config error, and the transport reuses the
shared TLS context.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
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 b6d9189. Configure here.

Comment thread server/clients/mcp_source.py Resolved
zlareb1 and others added 9 commits December 1, 2026 18:13
A listing that left a respelled row out of an earlier page now keeps every
later page incomplete. Output validation of up to megabytes runs in a
worker thread, since an unbounded array took seconds on the event loop.
The receipt fingerprint needs no cap, size checks serialize once, a DELETE
answered 404 has a positive test, and llms.txt follows the page's new
first sentence.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: zlareb1 <lareb.zafar@clickhouse.com>
ClientSession.call_tool validated the whole structured result on the event
loop before Loom's size check, so the threaded validation did not take that
cost off the loop. Tool calls now go through send_request, and the only
validation is the size-capped one in a thread. Partial listing state
follows each listing's cursor, so another listing cannot mark it complete. A
lone surrogate in the configuration is a config error, and the fingerprint
is computed with the other construction checks.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: zlareb1 <lareb.zafar@clickhouse.com>
Cursors were refused as a protocol error when a server issued one again,
so a server with stable offset cursors ended the session when a listing
restarted. Each listing or search from its first page is now a run: a
cursor continues the run that last issued it and is used once, a run that
issues one cursor twice is still a protocol error, and a skipped row leaves
the rest of its run partial. The size check no longer sorts keys.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: zlareb1 <lareb.zafar@clickhouse.com>
A restarted listing could be handed a cursor an earlier partial run still
held; taking it over dropped the partial state, so the earlier listing could
end complete with a row left out. The run that takes the cursor over now
inherits that state.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: zlareb1 <lareb.zafar@clickhouse.com>
One test now covers a second listing that issues its own cursor and one
that takes over the partial listing's cursor, and the client page's
paragraphs wrap to the page's width.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: zlareb1 <lareb.zafar@clickhouse.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: zlareb1 <lareb.zafar@clickhouse.com>
The constructor passed the function-length gate's 50-statement limit; its
configuration checks now live in _checked_configuration, which returns the
selected ids and the fingerprint.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: zlareb1 <lareb.zafar@clickhouse.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: zlareb1 <lareb.zafar@clickhouse.com>
The mapping check pairs a cursor argument with a cursor path, so a tool call
never receives a cursor for a mapping without one.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: zlareb1 <lareb.zafar@clickhouse.com>

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