Skip to content

Add a bounded outbound MCP read client - #1194

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

zlareb1 wants to merge 37 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):

  • Not for changelog (changelog entry is not required)

Changelog entry

None: no operation, worker or setting reaches this client yet; the integration that does carries the entry.

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.

Dependencies: mcp (the protocol's official Python SDK) carries Streamable HTTP and SSE framing, session and protocol-version negotiation, and the typed messages; jsonschema and referencing check approved tool schemas and results. Through mcp the image also gains sse-starlette, python-multipart, httpx-sse, rpds-py and the JSON Schema specification packages. The alternative is a hand-written JSON-RPC client over the existing httpx: no new packages, but Loom would own the framing, session lifecycle and every protocol revision, which is where interoperability fails; that cost is larger than the added packages, which Dependabot and the dependency review track.

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 (337 cases in the four focused files on the head, including a stateful server whose server-to-client stream stays quiet longer than one request timeout and a held notification answer that ends at the request timeout, 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.
  • No generated file is affected (scripts/codegen/docs_reference.py --check passes).
  • 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
Adds security-sensitive outbound HTTPS and credential handling, but it is bounded, fail-closed, and not yet wired into production source sync or publication paths.

Overview
Introduces an internal outbound MCP source client in server/clients/mcp_source.py plus docs/architecture/mcp-source-client.md, linked from the document-sources architecture page. This is a prerequisite only: no new source kinds, operations, workers, or stored configuration.

The client talks to a single pinned HTTPS Streamable HTTP endpoint via the official mcp SDK, using pinned_target for DNS/TLS identity, no redirects, and an injected validate_access hook around requests and response streaming. Reads are constrained by operator-approved resource IDs, tool names, and a restricted JSON Schema subset; it supports resources/list|read and explicitly mapped tool search/read, returning in-memory evidence and read receipts (content and config hashes) without writing knowledge documents.

Dependencies added: mcp, jsonschema, referencing, and dev types-jsonschema. Large unit suites cover protocol behavior, cancellation/deadline draining, and TLS/SSE against synthetic FastMCP servers.

Reviewed by Cursor Bugbot for commit 2964d1d. 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 3, 2026 12:06pm UTC
loom-telemetry Ready Ready Preview Dec 3, 2026 12:06pm 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 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.

Stale Bugbot comment from a previous run.

Comment thread server/clients/mcp_source.py Resolved
zlareb1 and others added 10 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>
main retired the hand-kept llms.txt; the client page's own summary now feeds the documentation index.

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 8ad8ea8. 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.

Mapping selectors skip output schema types

Medium Severity

Construction treats path shape as enough for a mapping to succeed, but evidence extraction always requires string identity, title, text, and URI values. An output schema can pin those selector targets to another type, so a mapping that cannot produce evidence is still accepted and only fails on the first read or search, which also ends the session.

Additional Locations (2)
Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 8ad8ea8. Configure here.

zlareb1 and others added 4 commits December 3, 2026 11:39
A stateful server's server-to-client stream may stay quiet longer than
one request may take; reads now wait out the session deadline while
ClientSession still bounds each request's answer. A control character
in a returned string is a schema error, not a limit, and the document
sources page links the client page.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: zlareb1 <lareb.zafar@clickhouse.com>
The session-length read timeout now applies to the server-to-client
GET alone, so a held notification answer, a held reply to a server
request and the closing DELETE stay bounded by request_seconds. Tests
pin that the idle test opens a GET stream, that a held 202 ends at the
request timeout, and how a returned string's control character and
size are refused.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: zlareb1 <lareb.zafar@clickhouse.com>
The three network tests build their client through one helper, and the
idle-stream comment says the client opens the GET stream.

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>

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