Skip to content

get_canister_candid: read one method or a summary instead of the whole interface - #222

Closed
aterga wants to merge 6 commits into
mainfrom
arshavir/ecstatic-franklin-tlxclv
Closed

aterga wants to merge 6 commits into
mainfrom
arshavir/ecstatic-franklin-tlxclv

Conversation

@aterga

@aterga aterga commented Oct 29, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

get_canister_candid was unusable on a canister with a large interface. The Open Cloud engine registry (q6cfj-fyaaa-aaaar-qb77q-cai, declared by https://opencloud.org) publishes a ~71 KB .did with 119 methods, and the reply carried that text twice — as the first text block and again as structuredContent.candid — so the ~140 KB reply got truncated by the MCP client, and the model had to call again (paying the full size a second time) just to find the signature of listVisibleEngines.

This PR lets a model read one method of a 100-method canister in a single small reply, and makes a full-interface reply the .did itself plus a short note.

Related issues

Changes

  • methods: ["<name>", …] argument — returns only those methods, each with every type definition it uses, transitively (the closure candid_parser's own binding generators compute via chase_actor), printed as a small .did that parses and encodes against those methods, so it also works as canister_query's candid fallback. Init arguments are dropped. Names are trimmed and de-duplicated; a name the service does not declare is an error listing the declared names (capped at 100, then "and N more"), so a typo is repaired in one step.
  • view: "summary" argument — one i/N name : (args) -> (results) [query] line per method, type names unexpanded and no type definitions: the cheap first call on a big interface. With methods, a summary covers only those. view: "full" (the default) still returns the published text verbatim.
  • Numbered, closed summary lines make a cut-short reply visible. A client that trims a tool result does so after receiving it whole and tells the model only sometimes; a checksum cannot help a model that cannot recompute a hash, but a counter can be read. Every summary line carries i/N (N counting that reply's lines, so a methods-restricted summary numbers itself over its own length) and the listing ends with a // end of summary (N/N) line, which any cut removes, even one inside the last line. The summary notes say so after the fact, and the view and tool descriptions say it before the first call. Signatures are laid out at the maximum width, so an inline record of any size stays on its one numbered line (a 600-field record pins it) rather than wrapping onto unnumbered continuation lines.
  • No more double shipping. The structured output no longer carries the interface text at all; it describes the first text block instead: view, the methods it is restricted to, candid_bytes (the complete interface's size) and method_count, next to the unchanged oql / api_doc_available / declared_by / declared_at. Of the two options weighed, dropping the text unconditionally (rather than above a size threshold) keeps the declared outputSchema identical for every reply — no field flips presence on a size boundary a client cannot predict — and guarantees no reply is ever the interface twice. The text block is the carrier, which the tool description, the schema and the README all say. Documented in GetCandidOutput's doc comment and the README's Tools section.
  • The restricted views append one short note saying what the block covers and how to get the rest (methods / view / the complete size); the OQL and API-doc notes are unchanged.
  • Everything a reply states now comes from one parse of the untrusted interface (render_candid), on the deep stack and behind guard_candid_text like its siblings; the OQL and API-doc predicates are shared with has_oql / api_doc_method so the flags cannot drift. The full view used to parse the interface twice.
  • The reply assembly is a pure function (candid_reply), testable without a replica.
  • CandidView is #[schemars(inline)], so the tool schema spells out full / summary in place rather than behind a $ref into $defs.
  • README: the tool table row, the structured-content preamble (the one deliberate exception), and the typical-flow step 5.
  • Merged main (Bound what one /oauth/authorize request stores in its pending connect #221, Say deploying happens with the icp CLI or a proxy deployment service #223, Fix the clippy warnings stable 1.97 reports on main #224, Privacy draft: per-app authorization lifetime is five minutes, not one hour #225, Describe open_app as acting in ICP apps so deferred-loading agents find it #226); the one conflict was the server instructions, where main's rewording is kept and this branch's CANISTERS clause is re-applied.

Testing

  • cargo build --locked --all-targets
  • cargo test --locked --all-targets (whole workspace green on the merged head)
  • cargo fmt --all / cargo clippy --all-targets (warning-free on the merged head, which carries Fix the clippy warnings stable 1.97 reports on main #224)
  • npm test --prefix monitoring/mcp-status (dashboard unchanged)
  • POCKET_IC_BIN=… cargo test --locked -p imcp2-core --features e2e e2e_canister_tools — 5 passed, the new case included, against the v15.0.0 server (digest-checked as in CI)

New tests:

  • calls::tests::render_candid_* (5): verbatim full view with the flags from the same parse; summary lines (sorted by name — the Candid grammar sorts a service's methods — numbered i/N in order and closed by the end line, mode kept, a 600-field inline record on one line, restricted and de-duplicated selections numbered over their own length); the restricted .did carries exactly the types the methods use (through a variant into a recursive record; not the unused type, the named func type, or the init-arg type), parses, resolves the methods and encodes arguments identically to the full interface; unknown / empty selections; and that every view but the verbatim one needs a parseable interface (guard trip, parse error, no service) while the verbatim one survives all three.
  • tools::tests::get_canister_candid_advertises_its_views_and_never_repeats_the_interface pins the advertised input schema (methods, inlined view values, no $defs) and the output schema (candid_bytes, method_count, … and no candid).
  • tools::tests::candid_reply_puts_the_rendering_first_and_the_text_only_there pins the block layout and the notes of all four view/selection combinations (including the closing-line tell in the summary notes), and that a full reply is the .did plus short notes.
  • e2e_canister_tools::candid_views_read_one_method_without_the_whole_interface drives the four shapes over a real MCP session against a PocketIC canister, including the unknown-method error and the discoverability gate running first.

Measured on the canister that motivated this

Read from mainnet with this branch's render_candid (a throwaway test, not committed), on q6cfj-fyaaa-aaaar-qb77q-cai:

Call First text block Notes
default (view: "full") 71,078 bytes the published .did, 119 methods — and no second copy in structuredContent any more
view: "summary" 7,618 bytes 119 signature lines and the closing line; 6,746 measured before numbering, plus the 844 bytes the 1/119 … 119/119 counters add and the 28-byte // end of summary (119/119) line
methods: ["listVisibleEngines"] 456 bytes the method plus the 4 type definitions it uses
methods: ["listEngines"] (a typo) 2,022-byte error names the unknown method and lists 100 of the 119 declared ones, "and 19 more"

The one-method reply, verbatim:

type EngineId = text;
type SubscriptionId = nat;
type Timestamp = int64;
type VisibleEngine = record {
  id : EngineId;
  platform_domain : opt text;
  subscription_id : opt SubscriptionId;
  owner : principal;
  subnet_id : opt principal;
  engine_operator_id : opt principal;
  created_at : Timestamp;
  deleted_at : opt Timestamp;
  all_in_one : opt bool;
  node_ids : vec principal;
};
service : { listVisibleEngines : () -> (vec VisibleEngine) query }

Checklist

  • I have read the Contributing guidelines.
  • Docs (README / comments) updated for any user-visible change.
  • No secrets, credentials, or internal-only information are included.

🤖 Generated with Claude Code

https://claude.ai/code/session_01VP2vTFU9SfBJ9yharm2fuJ

…e interface

A canister with a large interface made the tool unusable: the Open Cloud
engine registry (q6cfj-fyaaa-aaaar-qb77q-cai) publishes a ~71 KB `.did`
with 119 methods, and the reply carried it twice — as the first text
block and again as `structuredContent.candid` — so a ~140 KB reply got
truncated by the client, and the model paid for it a second time just to
find one method's signature.

Two arguments narrow the read:

* `methods: ["<name>", …]` returns only those methods, each with every
  type definition it uses (transitively, the closure candid_parser's own
  binding generators compute), printed as a small `.did` that parses and
  encodes against those methods — so it also serves as canister_query's
  `candid` fallback. Init arguments are dropped. A name the service does
  not declare is an error listing the declared names (capped), so a typo
  is repaired in one step.
* `view: "summary"` lists one `name : (args) -> (results) [query]` line
  per method, type names unexpanded and no definitions: the cheap first
  call on a big interface, before asking for one method.

The default view still returns the published text verbatim.

The structured output no longer carries the interface text at all. It
describes the first text block instead — `view`, the `methods` it is
restricted to, `candid_bytes` (the complete interface's size) and
`method_count` — next to the unchanged capability flags and declaration
fields. Dropping the text unconditionally, rather than above a size
threshold, keeps the declared outputSchema the same for every reply:
no field flips presence on a size boundary a client cannot predict, and
no reply is ever the interface twice.

Everything a reply states now comes from ONE parse of the untrusted
interface (the OQL and API-doc predicates are shared with has_oql /
api_doc_method, so the flags cannot drift), where the full view used to
parse it twice. The reply assembly is a pure function, testable without
a replica.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_01VP2vTFU9SfBJ9yharm2fuJ

Copilot AI 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.

🟢 Approval recommended

No active review issues were identified for the focused Candid views and structured-output changes.

No open issues 🎉

What changed in this PR

This PR makes large canister interfaces easier to inspect through get_canister_candid, adding focused views and removing duplicate interface text from structured output.

Changes:

  • Adds method filtering with transitive type definitions and a compact summary view, while preserving verbatim full-interface reads by default.
  • Keeps interface text only in the first content block; structured output reports metadata and capability flags from a shared parse.
  • Updates usage guidance and adds unit and end-to-end coverage for rendering, response structure, errors, and discoverability gating.
File Description
README.md Documents the new views, output structure, and recommended workflow.
crates/​imcp2-core/​src/​tools.rs Integrates view arguments, extracts reply assembly, and tests schemas and content blocks.
crates/​imcp2-core/​src/​e2e_canister_tools.rs Adds MCP-session coverage for views, unknown methods, and discoverability gating.
crates/​imcp2-core/​src/​calls.rs Implements rendering, method selection, shared capability detection, and unit tests.

Review effort: Balanced

@aterga
aterga marked this pull request as ready for review October 30, 2026 08:45
@aterga
aterga requested a review from a team October 30, 2026 08:45
Comment thread crates/imcp2-core/src/calls.rs Outdated
Comment on lines +77 to +79
/// One `name : (args) -> (results)` line per method, type names left
/// unexpanded and no type definitions: a cheap index of a large interface.
Summary,

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

I would return the method names only, returning more than that only risks AI hallucinating arguments it doesn't know the types for.

One conflict, in SERVER_INSTRUCTIONS: main's rewording (#223, #226) is kept
and this branch's CANISTERS clause about `view: "summary"` and `methods` is
re-applied to it.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_01VP2vTFU9SfBJ9yharm2fuJ
… visible

A client that trims a tool result does so after receiving it whole, and
tells the model about it only sometimes. A checksum cannot help the
model — it cannot recompute a hash over what it was shown — but it can
read a counter. So every line of the `summary` view now carries one:

    17/119 getEngine : (EngineId) -> (opt Engine) query

`i/N` counts the lines of that reply, not the service's methods, so it
also holds for a summary restricted with `methods`: a reply whose last
visible line is not `N/N`, or whose sequence skips, was cut short. The
summary notes say so, the `view` argument's description and the tool
description say it before the first call, and the README documents the
form.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_01VP2vTFU9SfBJ9yharm2fuJ
Copilot AI balanced review requested due to automatic review settings November 3, 2026 14:23

Copilot AI 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.

🟡 Changes recommended

The leading completion counter can mask truncation that removes a method’s mode, while long signatures can wrap onto unnumbered lines and violate the one-line-per-method format.

2 open issues

Review effort: Balanced

Comment thread crates/imcp2-core/src/calls.rs Resolved
Comment thread crates/imcp2-core/src/calls.rs Resolved
…p a signature

Two review findings on the numbered summary, both real:

* The counter led each line, so a cut inside the LAST line kept `N/N`
  visible while losing the line's tail. The listing now ends with a
  `// end of summary (N/N)` line that any cut removes, and the notes
  and the argument text tell the model to look for it.

* Signatures were laid out at a fixed 10,000-column width, so a valid
  inline record past it wrapped onto unnumbered continuation lines: a
  complete summary that looked cut short. They are now laid out at the
  maximum width. The printer breaks a group only where it would overrun
  the width and never adds to it, so every signature is one line
  whatever its length and the pass stays linear. A 600-field record
  pins it.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_01VP2vTFU9SfBJ9yharm2fuJ
Copilot AI balanced review requested due to automatic review settings November 3, 2026 14:36

Copilot AI 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.

🔵 Needs a closer look

Parser-thread creation failure now rejects default full-interface reads instead of returning the already-fetched text with unparsed defaults, regressing the previous fallback behavior.

No open issues 🎉

1 previously missed issue

In code that hasn't changed since last review

Medium severity Preserve interface fallback when parser thread creation fails

crates/​imcp2-core/​src/​calls.rs:1120

If the parser thread cannot be created (for example, under OS thread or virtual-memory limits), this now fails even the default full-interface read, although the published text has already been fetched. Previously, has_oql and api_doc_method degraded to false/None in this case and the interface was still returned. Preserve that fallback by returning Ok(unparsed()) when verbatim is true; only the views that require parsing need to return this error.

2 resolved since last review

Review effort: Balanced

…be spawned

render_candid turned a failure to spawn the deep-stack parse thread into
an error for every view, the default verbatim one included, although the
published text was already in hand. Before this branch that read went
through has_oql and api_doc_method, which degrade to false / None on the
same failure and leave the interface to be returned. Restore that: the
verbatim view comes back with nothing established about it, and only a
view that needs the parse is an error naming the read that still works.
Caught by review.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_01VP2vTFU9SfBJ9yharm2fuJ
Copilot AI balanced review requested due to automatic review settings November 3, 2026 14:48

Copilot AI 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.

🔵 Needs a closer look

Human assessment is needed to evaluate server memory-exhaustion and worker-blocking risks from unbounded summary expansion and quadratic method selection.

No open issues 🎉

Review effort: Balanced

…y scan

The selection was matched against the service's methods by scanning: a
request naming n methods against a service declaring m cost n × m
comparisons, which a request with thousands of names against a canister
publishing thousands of methods turns into real CPU on the worker. The
names already go through a set to de-duplicate them; keep that set and
look the declared names up in one of their own, so the cost is
(n + m) log n. Review flagged the quadratic selection.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_01VP2vTFU9SfBJ9yharm2fuJ
Copilot AI balanced review requested due to automatic review settings November 3, 2026 15:03

Copilot AI 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.

🔵 Needs a closer look

Human assessment is needed because summary rendering can amplify untrusted interface metadata into gigabytes of in-memory output, potentially exhausting server memory.

No open issues 🎉

Review effort: Balanced

aterga pushed a commit that referenced this pull request Nov 3, 2026
…output (#229)

* fix(get_canister_candid): carry the interface text in the structured output

Clients that read structuredContent (Claude Code among them) drop the text
blocks, so since #222 they received the interface's size and flags but never
the .did itself. Add the `candid` field back to GetCandidOutput.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* test(get_canister_candid): expect the candid field in the output schema

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* test(get_canister_candid): pin candid as a string; document the oversized renderings

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>

aterga commented Nov 10, 2026

Copy link
Copy Markdown
Collaborator Author

Superseded by #227 (merged), which reads a commented sub-service for the methods the API doc names instead of a numbered summary, with #229 carrying the interface text in the structured output. Closing this one.


Generated by Claude Code

@aterga aterga closed this Nov 10, 2026
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.

4 participants