Skip to content

get_canister_candid: read a commented sub-service for the methods the API doc names - #227

Merged
aterga merged 6 commits into
mainfrom
arshavir/candid-service-subset
Nov 3, 2026
Merged

aterga merged 6 commits into
mainfrom
arshavir/candid-service-subset

Conversation

@aterga

@aterga aterga commented Nov 3, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

An alternative to #222 for the same problem, explored as its own PR: 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 text and again as structuredContent.candid — so the ~140 KB reply got truncated by the MCP client, and the model paid for it a second time just to find the signature of listVisibleEngines.

The flow this PR serves needs no summary of the interface: open_app, then get_canister_api_doc — whose guide already covers the methods a caller needs and names them — then get_canister_candid with methods for just those, which comes back as a small valid .did with the interface's own comments on the service, those methods, their types and fields.

Related issues

Alternative to #222 (which adds a view: "summary" listing instead of relying on the API doc).

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 with the // comments the interface carries on the service, those methods, the type definitions and their fields — nested records and variants included, inside opt and vec too, and inside a method's own inline argument and result records — in the interface's own declaration order. The parser attaches a comment to the declaration, method or field that directly follows it (not one separated by a blank line, not a trailing one). The printing is a small doc-aware printer of this crate's own (print_subset), because candid's compile_with_docs descends into a record that sits directly in a type or a field only and orders definitions alphabetically; anything carrying no field comment is still laid out by candid's printer. Init arguments are dropped, so the result is a plain service : { … } that parses and encodes against those methods — it also works as canister_query's candid fallback. Names are trimmed, de-duplicated and matched by set lookup; a name the service does not declare is an error listing every declared name.
  • 5 KB limit, comments included (MAX_SERVICE_SUBSET_BYTES), for every reply. A selection of several methods over it is refused with an error naming the size, the limit, the way out ("ask for fewer at a time") and every method the service declares; a single method is always answered, with its comments stripped if that is what it takes, flagged as a best effort. With methods omitted, a complete interface over the limit is refused the same way (pass methods, with the names the API doc gives); one that keeps to the limit comes back verbatim as before. The one exception is an interface that cannot be parsed: there is no method list to offer for it, so it comes back whole whatever its size, with a note saying why. The method list in those errors keeps to the same limit — every name held to it, the first included, and omitted names counted even when none fits — so a service with thousands of methods, or one huge identifier, cannot turn the error into the reply size the limit exists to avoid.
  • No more double shipping. The structured output no longer carries the interface text at all; it describes the text instead: methods (what it is restricted to), bytes (its size, comments included), best_effort (comments stripped to fit), next to the unchanged oql / api_doc_available / declared_by / declared_at. Dropping the text unconditionally keeps the declared outputSchema identical for every reply and guarantees no reply is ever the interface twice; the tool description, the schema and the README say the text is the carrier.
  • A restricted reply appends one short note saying what it covers (or that its comments were stripped and why) and the complete interface's size; the OQL and API-doc notes are unchanged.
  • Everything a reply states comes from one parse of the untrusted interface (render_candid), on the deep stack and behind guard_candid_text like its siblings, parsed from the syntax tree (IDLProg) so the comments survive; the OQL and API-doc predicates are shared with has_oql / api_doc_method so the flags cannot drift. The verbatim read survives an interface that cannot be parsed, or for which no parse thread could be spawned, exactly as has_oql / api_doc_method degrade. A service reached through type aliases keeps its method comments however long the chain: the walk is bounded by the declaration count, which an acyclic chain cannot exceed.
  • The reply assembly is a pure function (candid_reply), testable without a replica.
  • README: the tool table row, the structured-content preamble (the one deliberate exception), and the typical-flow step 5 (API doc first, then methods). Server instructions: one clause on methods.

Testing

  • cargo build --locked --all-targets
  • cargo test --locked --all-targets (whole workspace green)
  • cargo fmt --all / cargo clippy --all-targets (warning-free)
  • 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_* (6): verbatim read with the flags from the same parse; a restricted .did keeps the comments on the service, the method, the type, its fields, a nested record's fields, the fields of records inside vec and opt, and the fields of a method's own inline argument and result records, in the interface's own order, 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; a 13-alias chain to the service keeps its method comment; the limit refuses a complete interface over it and several methods over it (listing every method), and strips one, including one still over the limit stripped; unknown and empty selections, with the method list cut at the limit on a 2,000-method service and a name too big for the budget counted as omitted; and that only a restricted read needs a parseable interface (guard trip, parse error, no service) while the verbatim read survives all three, whatever its size.
  • tools::tests::get_canister_candid_advertises_methods_and_never_repeats_the_interface pins the advertised input schema (methods, the doc-first description) and the output schema (bytes, best_effort, methods, … and no candid).
  • tools::tests::candid_reply_puts_the_interface_first_and_the_text_only_there pins the layout and notes for the complete and the restricted read, comments included, that a full reply is the .did plus short notes, and the note on an oversized interface that could not be parsed.
  • e2e_canister_tools::candid_methods_read_one_commented_method_without_the_whole_interface drives the complete and the restricted read over a real MCP session against a PocketIC canister whose interface now carries a comment on set_message, including the unknown-method error and the discoverability gate running first.

Measured on the canister that motivated this

With this branch's render_candid over the registry's published interface (a throwaway test, not committed):

Call Text Notes
default (no methods) refused the published .did is 71,078 bytes with 119 methods, so the error names the size, the limit and all 119 methods (about 2.5 KB) instead of a reply the client would cut short
methods: ["listVisibleEngines"] 757 bytes the method, the 4 type definitions it uses, and the author's 4-line comment on VisibleEngine (below)
methods: ["getEngine"] / ["createEngine"] / ["adoptEngine"] 1,507 / 2,950 / 4,960 bytes comments kept, under the limit
methods: ["listVisibleEngines", "getEngine", "createEngine"] 3,671 bytes three related methods share their types, so together they stay under the limit
every single-method read 7 of 119 stripped at 5 KB the limit strips comments on 7 methods; the largest kept intact is changeEngineNodes at 4,980 bytes — the constant is one place to tune

The registry keeps its opt record comments on the enclosing fields, which both printers carry, so these numbers did not move with the printer change. The one-method reply, verbatim:

type EngineId = text;
type SubscriptionId = nat;
type Timestamp = int64;
// An Engine as listVisibleEngines returns it. platform_domain is the engine's
// platform domain, <slugify(name)>--<slug>.<base-domain>, built on read from
// its current name; null while no base domain is set (setPlatformBaseDomain).
// A new or renamed engine's domain can still be registering.
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

… API doc names

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.

The flow this serves: open_app, then get_canister_api_doc — whose guide
covers the methods a caller needs and names them — then
get_canister_candid with `methods` for just those. No summary of the
interface is needed on the way.

`methods: ["<name>", …]` returns only those methods, each with every
type definition it uses (transitively, the closure candid_parser's own
binding generators compute), printed WITH the interface's own `//`
comments on those methods, types and fields. The parser attaches a
comment to the declaration, method or field that directly follows it,
and candid's printer takes them back through `DocComments`, so the
sub-service is a valid `.did` that parses and encodes against those
methods, and reads as the author wrote it. Init arguments are dropped.

The text keeps to 5 KB, comments included. Over it, several methods
are refused with every declared method listed, so the caller asks for
fewer at a time; a single method is always answered, with its comments
stripped if that is what it takes, flagged as a best effort. A name the
service does not declare is an error listing the declared names, that
list itself kept to the limit. Omitted, `methods` reads the complete
interface verbatim as before.

The structured output no longer carries the interface text at all. It
describes the first text block instead — the `methods` it is restricted
to, `bytes` (comments included), `best_effort` — next to the unchanged
capability flags and declaration fields, so a reply is never the
interface twice and the declared outputSchema is the same for every
reply. Everything a reply states comes from ONE parse of the untrusted
interface, on the deep stack behind the usual guard; the OQL and
API-doc predicates are shared with has_oql / api_doc_method so the
flags cannot drift. The reply assembly is a pure function, testable
without a replica.

On the registry: listVisibleEngines with its comments is 754 bytes,
three related methods together 3,676, and the limit strips comments on
7 of its 119 single-method reads.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_01VP2vTFU9SfBJ9yharm2fuJ
@aterga
aterga requested review from sea-snake and a balanced review from Copilot November 3, 2026 15:06
@aterga
aterga marked this pull request as ready for review November 3, 2026 15:06
@aterga
aterga requested a review from a team November 3, 2026 15:06

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

An oversized first method name bypasses the output budget, while nested types and long service-alias chains silently lose comments without reporting degraded output.

3 open issues
What changed in this PR

This PR makes large canister interfaces easier to read through get_canister_candid, using API-doc method names to request a focused interface instead of adding the summary view proposed in #222.

Changes:

  • Adds method selection with transitive type dependencies and interface comments, plus size-based refusal or comment stripping.
  • Removes duplicated interface text from structured output, replacing it with metadata about the first text block.
  • Updates usage guidance and adds unit and end-to-end coverage.
File Description
README.md Documents method selection, size handling, and the API-doc-first flow.
crates/​imcp2-core/​src/​tools.rs Integrates restricted replies, updates tool guidance, and tests output layout and schemas.
crates/​imcp2-core/​src/​e2e_canister_tools.rs Tests commented method selection, output metadata, and discoverability enforcement.
crates/​imcp2-core/​src/​calls.rs Implements interface projection, comment extraction, size handling, and rendering tests.

Review effort: Balanced

Comment thread crates/imcp2-core/src/calls.rs Resolved
Comment thread crates/imcp2-core/src/calls.rs Resolved
Comment thread crates/imcp2-core/src/calls.rs Resolved
Comment thread crates/imcp2-core/src/calls.rs Resolved
Comment thread crates/imcp2-core/src/tools.rs Resolved
Comment thread crates/imcp2-core/src/calls.rs Resolved
Review on the sub-service read found three gaps and a term:

* Field comments inside a record or variant that sits in an `opt` or
  `vec` were lost: candid's `compile_with_docs` descends into a record
  that sits directly in a type or a field only. The sub-service is now
  printed by a small doc-aware printer of its own that follows the
  comments through those wrappers, keeps the interface's declaration
  order instead of the printer's alphabetical one, and carries the
  service's own comment; what carries no field comment is still laid
  out by candid's printer.
* A service reached through more than eight type aliases lost its
  method comments to a fixed hop limit while `best_effort` stayed
  false. The walk is now bounded by the declaration count, which an
  acyclic (type-checked) chain cannot exceed.
* The declared-method list skipped its budget for the first name, so a
  single huge identifier could push an error past the limit the list
  exists to keep. Every name is now held to the budget, and omitted
  names are counted even when none fits.
* "Block" was new terminology for what the README already calls the
  text and the structured object; the new text says that instead.

Also: the requested methods are matched by set lookup, not by scan, so
a request naming thousands against a service declaring thousands costs
(n + m) log n rather than n × m.

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:23
…ng its methods

Review asked that the default read keep to the same limit as a
restricted one: a complete interface over 5 KB would only be cut short
by the client, so it is now refused with the size, the limit, the way
out (`methods`, with the names the API doc gives) and every method the
service declares. An interface that cannot be parsed has no method list
to offer and comes back whole whatever its size, with a note saying so.

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.

🟡 Changes recommended

Inline argument and result field comments are silently dropped, losing units or constraints while incorrectly reporting best_effort: false.

1 open issue
3 resolved since last review

Review effort: Balanced

Comment thread crates/imcp2-core/src/calls.rs Resolved
Copilot AI balanced review requested due to automatic review settings November 3, 2026 15:27
…t and result records

A method whose argument or result is an inline record or variant can
carry comments on its fields; those were dropped, since a signature was
still laid out by candid's printer. The sub-service printer now lays
such a signature out itself, one field per line with its comment, as
it already does for a type definition. Review found it.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_01VP2vTFU9SfBJ9yharm2fuJ
sea-snake
sea-snake previously approved these changes Nov 3, 2026
The test that pins the comments inside a method's own argument and result
records borrowed the service from a temporary, which did not compile as a
test target; the previous commit went up before that was caught.

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.

🔵 Needs a closer look

Inline argument/result field comments are still lost despite best_effort: false, and unbounded unknown-method names can cause errors to be truncated before recovery guidance.

No open issues 🎉

1 previously missed issue

In code that hasn't changed since last review

Medium severity Limit unknown method names in error responses

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

Unknown method names are echoed without a size limit, so one 64 KiB name or many unknown names can cause the client to truncate the error before reaching the declared-method guidance. Budget both name lists within the error limit, count omitted unknown names, and reserve space for recovery guidance. Add regression cases for a long unknown name and many unknown names.

1 resolved since last review

Review effort: Balanced

Copilot AI balanced review requested due to automatic review settings November 3, 2026 15:31
sea-snake
sea-snake previously approved these changes Nov 3, 2026
The names a caller asks for that the service does not declare were
repeated in the error without a limit, so a flood of them, or one huge
name, could push the declared names (the useful part) past what a client
shows. They now share the budgeting the declared list uses, with a small
share of the limit, and the rest is counted. Review found it.

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.

🔵 Needs a closer look

Human assessment is needed because a moderate-severity finding about potentially truncated error messages was omitted from the published review.

No open issues 🎉

1 resolved since last review

Review effort: Balanced

Copilot AI balanced review requested due to automatic review settings November 3, 2026 15:36
@aterga
aterga merged commit 1ebc624 into main Nov 3, 2026
17 checks passed

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

The review identifies no active issues with the method-filtered Candid rendering changes.

No open issues 🎉

Review effort: Balanced

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