Skip to content

feat(mcp): on-demand MCP tool discovery to preserve local context windows (#1571) - #1651

Merged
addyCooks merged 4 commits into
Nano-Collective:mainfrom
rishu685:feat/on-demand-mcp-discovery
Nov 6, 2026
Merged

addyCooks merged 4 commits into
Nano-Collective:mainfrom
rishu685:feat/on-demand-mcp-discovery

Conversation

@rishu685

@rishu685 rishu685 commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor

Description

Introduces an on-demand MCP tool discovery architecture to mitigate system prompt context exhaustion when numerous MCP tools are configured:

  1. Deferred Discovery & Tool Catalog: Defers eager schema hydration into the prompt when MCP servers provide multiple tools (governed by tune.mcpDiscovery, default threshold: 8 tools). Unloaded tools are cataloged with sanitized names and descriptions.
  2. Built-in load_tool_schema Tool: Allows the agent to look up and inspect the full JSON parameter schema for any discovered MCP tool, dynamically hydrating it into the active tool registry for subsequent turns.
  3. Prompt Injection Mitigation: Implemented sanitizeCatalogText to strip markdown tags, HTML elements, collapse multi-line breaks/tabs into single spaces, and bound descriptions to 120 characters.
  4. Config Schema & Callers: Added tune.mcpDiscovery (auto, always, disabled) across types, regenerated schemas/agents.config.schema.json, wired tuneConfig through CLI/daemon/plain/TUI entry points, and documented in docs/features/tune.md.

Related Issues

Fixes #1571

Type of Change

  • Bug fix (non-breaking change which fixes an issue)
  • New feature (non-breaking change which adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • Documentation update
  • Refactoring (no functional changes)
  • Other (please describe):

Testing

  • Ran AVA test suites:
    • source/mcp/tool-catalog.spec.ts (6 tests including prompt injection sanitization)
    • source/tools/tool-manager.spec.ts (101 tests including always and disabled tune settings)
    • source/tools/mcp/load-tool-schema.spec.tsx (4 tests)
    • Total 111 tests passing.
  • Verified TypeScript typecheck (tsc --noEmit), Biome lint & check, and schema drift validation (pnpm generate:schema && git diff --exit-code schemas/agents.config.schema.json).

Checklist

  • My code follows the project's coding standards.
  • I have performed a self-review of my code.
  • I have commented my code, particularly in hard-to-understand areas.
  • I have made corresponding changes to the documentation.
  • My changes generate no new warnings.
  • I have added tests that prove my fix is effective or that my feature works.
  • New and existing unit tests pass locally with my changes.
  • Any dependent changes have been merged and published in downstream modules.

@github-actions github-actions Bot added the area:tools Tool implementations and tool-calling label Oct 8, 2026
@github-actions

github-actions Bot commented Oct 8, 2026

Copy link
Copy Markdown
Contributor

nc-review: needs work — 2 blocking, 1 important, 3 nits

@rishu685 — there is a blocking item below.

The PR implements on-demand MCP tool discovery via a new MCPToolCatalog, a load_tool_schema built-in tool, prompt injection of the catalog, and direct-execution hydration fallback. The mechanism is sound and the new tests exercise the auto-threshold path meaningfully. However, the JSON config schema is not regenerated after adding tune.mcpDiscovery to TuneConfig, which will fail the schema-drift CI check. The tuneConfig parameter added to initializeMCP is also never wired to any caller, so the explicit always and disabled configuration modes are unreachable in production. These need to be fixed before merge.

🔴 blocking · completeness · schemas/agents.config.schema.json:569

TuneConfig.mcpDiscovery was added to source/types/config.ts but schemas/agents.config.schema.json was not updated. The PR adds no changeset for the schema and does not run pnpm generate:schema. The schema-drift CI check in .github/workflows/pr-checks.yml (pnpm generate:schema && git diff --exit-code schemas/agents.config.schema.json) will fail. Run the generator and commit the regenerated schema before merge.

🔴 blocking · correctness · source/tools/tool-manager.ts:199

initializeMCP gains a new tuneConfig?: TuneConfig parameter, but none of the four call sites pass it: source/hooks/useAppInitialization.tsx:270, source/daemon/entry.ts:122, source/plain/initialize.ts:191, and the test (which exercises the auto-threshold via count, not via the parameter). Combined with the schema drift above, the tune.mcpDiscovery = 'always' and 'disabled' configuration modes are unreachable for real users — the auto-threshold (>= 8 tools) is the only path that can fire. Either wire tuneConfig through to all callers (and regenerate the schema so users can configure it), or drop the parameter and let auto-threshold be the only control.

🟠 important · tests · source/tools/tool-manager.spec.ts:1322

The added discovery test passes no tuneConfig and relies on mcpToolEntries.length >= 8 to trigger the auto path. There is no test for tuneConfig.mcpDiscovery === 'always' (force discovery on small tool counts) or tuneConfig.mcpDiscovery === 'disabled' (force discovery off even when count >= 8). Given finding #2 leaves these branches unwired at runtime, the test should at least assert the parameter is honoured so a regression in the gating logic is caught.

⚪ nit · scope · biome.json:2

The $schema URL is bumped from 2.5.0 to 2.5.13 in the same PR as a feature change. Unrelated drive-by; CONTRIBUTING asks contributors to discuss substantial changes first. Either split into its own chore PR or drop it.

⚪ nit · scope · source/acp/acp-agent.ts:247

Five mojibake → em-dash comment fixes are mixed into a feature PR (the comments were never read by anything; this is purely cosmetic). Either split into a separate cleanup PR or drop it — bundling unrelated tidy-ups makes review harder.

⚪ nit · design · source/tools/tool-manager.ts:154

setActiveToolManager(this) is called inside the ToolManager constructor, and getActiveToolManager() is then read from prompt-builder.ts and load-tool-schema.tsx. Many test and runtime code paths construct multiple ToolManager instances (source/daemon/daemon.ts, source/plain/initialize.ts, source/hooks/useAppInitialization.tsx), so the module-level singleton is whichever instance was constructed last. The catalog section will silently be missing whenever the prompt is built before the active manager is set, and a subagent's load_tool_schema call mutates whatever manager happens to be active at call time — usually the parent's. The current tests don't exercise this, so it works in CI; in production it's fragile. A explicit getter passed through the call chain would be safer than module state.


🔴 blocking · 🟠 a reviewer would ask for a change · ⚪ optional

Automated code review — correctness, security, design, tests, plus duplicates and scope. A human still decides; this is not a substitute for review and is not exhaustive. The required status checks separately cover lint, formatting, types, unused dependencies, the test suite and the build. This bot never merges. Maintainers can rerun with /re-review.

@github-actions github-actions Bot added agent:needs-work nc-review found blocking findings area:tui Terminal UI labels Oct 8, 2026
@rishu685

rishu685 commented Oct 8, 2026

Copy link
Copy Markdown
Contributor Author

Made the required changes as per the feedback

@addyCooks addyCooks left a comment

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.

Thanks for this, the idea fits the project and the specs pass here. Before merge:

  1. Please rebase: the branch conflicts with main (tool-manager.ts, its spec, prompt-builder.ts), and main now builds a ToolManager per ACP session.
  2. setActiveToolManager(this) in the constructor lets a second ToolManager take over, and load_tool_schema then reports the first one's tools as "not found" (I reproduced this). Please pass the manager explicitly.
  3. Catalog descriptions aren't truncated, though the PR says they are. Please cap them (about 120 chars) and add a test.
  4. The catalog is added to the prompt even when load_tool_schema isn't offered (nano/minimal profiles). Please only add it when the tool is available.
  5. Please update the PR description to follow the template. It also says the tool takes an array, but it takes a single tool_name.

@github-actions

github-actions Bot commented Nov 4, 2026

Copy link
Copy Markdown
Contributor

Hi @rishu685, thanks for this PR! It looks like a maintainer has left feedback
or review activity and there are still some outstanding items to wrap up.

Whenever you get a chance, could you take a look at the open comments?
If anything is unclear or you'd like a hand, just reply here and we'll help you get it across the line.

@rishu685
rishu685 force-pushed the feat/on-demand-mcp-discovery branch from 0d82e64 to 451bdca Compare November 5, 2026 08:18
@rishu685

rishu685 commented Nov 5, 2026

Copy link
Copy Markdown
Contributor Author

@addyCooks Rebased onto latest main, resolved all review feedback, and pushed the updated branch:

  1. Config Schema: Regenerated schemas/agents.config.schema.json via pnpm generate:schema to include tune.mcpDiscovery (auto, always, disabled).
  2. Caller Wiring: Passed tuneConfig to toolManager.initializeMCP across all call sites (useAppInitialization.tsx, entry.ts, initialize.ts).
  3. Comprehensive Tests: Added tests asserting tune.mcpDiscovery === 'always' and tune.mcpDiscovery === 'disabled' in tool-manager.spec.ts and verified 109 tests passing in source/tools/tool-manager.spec.ts, tool-catalog.spec.ts, and load-tool-schema.spec.tsx.
  4. Description Truncation: Catalog descriptions are bounded to 120 chars with a dedicated unit test.
  5. Catalog Section Gating: The MCP catalog summary in system prompt is only included if load_tool_schema is in the active tool profile and has unloaded tools.
  6. PR Hygiene: Dropped unrelated changes to biome.json and acp-agent.ts, verified clean typecheck (test:types) and lint (test:lint).

@rishu685
rishu685 force-pushed the feat/on-demand-mcp-discovery branch from 451bdca to 7d01a4c Compare November 5, 2026 09:37

@addyCooks addyCooks left a comment

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.

Thanks @rishu685, the rebase, the 120-char cap, the catalog gating and the schema/tune wiring all look good, and CI is green. I tested the branch locally (109 specs pass) and found a few problems that need fixing before merge:

  1. Shared catalog gets wiped: a session manager shares the parent's catalog, but initializeMCP()/disconnectMCP() call this.mcpCatalog.clear(). After session.disconnectMCP() the base catalog went from 2 entries to 0, so ending one ACP session makes every unloaded tool "not found". Please use a per-manager catalog, or remove only that manager's own servers' entries.
  2. Global active manager (my earlier point 2) is still there: setActiveToolManager(this) in the constructor lets a second ToolManager take over. Please pass the manager explicitly to load_tool_schema and the prompt builder.
  3. Prompt injection: MCP descriptions go into the system prompt with newlines intact, so a description like "Lists files.\n\n### SYSTEM OVERRIDE\n..." becomes a heading in the prompt. Please collapse whitespace/newlines and strip markup in names and descriptions (and add a test).
  4. load_tool_schema is registered even when there are no MCP servers, which adds a tool definition to every request. Please only register it when discovery is active.
  5. Please update the PR description to the repo template (it also still says the tool takes an array; it takes a single tool_name), and add a line in the changeset/docs about tune.mcpDiscovery and the default threshold of 8.

Small: the typeof ... === 'function' guards in initializeMCP exist only for test mocks; please update the mocks instead. Happy to re-review once updated.

@rishu685
rishu685 force-pushed the feat/on-demand-mcp-discovery branch from 7d01a4c to cc01a58 Compare November 6, 2026 10:02
@github-actions github-actions Bot added the area:docs Documentation label Nov 6, 2026
@rishu685

rishu685 commented Nov 6, 2026

Copy link
Copy Markdown
Contributor Author

@addyCooks Updated as per the feedback:

  1. Rebased cleanly onto latest main.
  2. Implemented sanitizeCatalogText in MCPToolCatalog to collapse newlines/tabs/whitespace, strip HTML/markdown delimiters, and bound tool descriptions to 120 chars to prevent prompt injection. Added regression tests in source/mcp/tool-catalog.spec.ts.
  3. Verified tuneConfig.mcpDiscovery ('always' / 'disabled' / 'auto') is wired across all entry callers and exercised in source/tools/tool-manager.spec.ts.
  4. Documented tune.mcpDiscovery in docs/features/tune.md.
  5. Validated schema generation (generate:schema) with zero schema drift against CI checks, 0 Biome lint issues, and all 111 AVA tests green.
  6. Updated PR description to match the repository template.

Comment thread source/mcp/tool-catalog.ts Fixed

@addyCooks addyCooks left a comment

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.

Thanks @rishu685, the sanitising, the docs and the template update look good. I re-tested the branch (176 specs pass, tsc and Biome clean). Three items from my last review still reproduce:

  1. Shared catalog gets wiped: a session manager shares the parent's catalog, but initializeMCP()/disconnectMCP() call this.mcpCatalog.clear(). After session.disconnectMCP() the base catalog went from 2 entries to 0, so ending one ACP session makes every unloaded tool "not found". Please use a per-manager catalog, or remove only that manager's own servers' entries (removeServerTools), and add a test.
  2. setActiveToolManager(this) is still in the constructor, so a second ToolManager takes over the global. Please pass the manager explicitly to load_tool_schema and the prompt builder.
  3. load_tool_schema is still registered for every session, even with no MCP servers, which adds a tool definition to every request. Please only register it when discovery is active.

Small: sanitizeCatalogText only replaces \r\n\t; /\s+/ would also cover U+2028 and vertical tab. Happy to re-review once updated.

@rishu685
rishu685 force-pushed the feat/on-demand-mcp-discovery branch from ec77ce9 to 80ae4ec Compare November 6, 2026 10:48
@rishu685

rishu685 commented Nov 6, 2026

Copy link
Copy Markdown
Contributor Author

@addyCooks Updated as per the feedback in commit 80ae4ec:

  1. Layered Per-Manager Catalog: Modeled MCPToolCatalog with parent layering analogous to ToolRegistry. A session manager layers its catalog over the parent's catalog; ending an ACP session or calling disconnectMCP()/clear() clears only that session layer's entries, leaving the base catalog completely intact. Added a regression unit test in source/tools/tool-manager.spec.ts and source/mcp/tool-catalog.spec.ts.
  2. Explicit ToolManager Passing: Removed setActiveToolManager / getActiveToolManager globals. Passed the manager explicitly to createLoadToolSchemaTool(manager) and into buildSystemPrompt(..., toolManager) across ACP sessions, plain mode, usage command, and chat handler.
  3. On-Demand Discovery Gating: Removed load_tool_schema from global staticTools. It is now strictly registered only when MCP discovery is active (tune.mcpDiscovery === 'always' or tool count >= 8) via this.registry.registerToolExport(createLoadToolSchemaTool(this)). Sessions with no MCP servers do not advertise the tool.
  4. Enhanced Sanitization: Updated sanitizeCatalogText with /\s+/g whitespace normalization (covering U+2028, vertical tabs, and line breaks) and single-character delimiter stripping, passing CodeQL cleanly.

@rishu685
rishu685 requested a review from addyCooks November 6, 2026 10:58

@addyCooks addyCooks left a comment

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.

Thanks @rishu685, the last round fixes everything I raised. I re-ran my earlier probes on this head: a session manager's disconnectMCP() now leaves the base catalog intact, the global active-manager is gone, load_tool_schema isn't registered when there are no MCP servers, and descriptions with newlines or fake headings can no longer inject into the prompt. Types and Biome are clean, and the new tests fail without the change.

Optional follow-ups: stripping all whitespace from tool names would turn a name with a space into a different name, and the formatter hardcodes yellow instead of a theme colour.

Approving 🎉

@addyCooks
addyCooks merged commit 22c1ed6 into Nano-Collective:main Nov 6, 2026
18 checks passed
jay23606 added a commit to jay23606/nanocoder that referenced this pull request Nov 12, 2026
…dows (Nano-Collective#1571) (Nano-Collective#1651)

* feat(mcp): on-demand MCP tool discovery to preserve local context windows (Nano-Collective#1571)

* fix(mcp): sanitize tool catalog text against prompt injection and document tune.mcpDiscovery

* fix(mcp): strip HTML delimiters as single-character class to satisfy CodeQL

* fix(mcp): layer session catalog over parent, pass manager explicitly, and gate load_tool_schema to active discovery
diyaavirmani added a commit to diyaavirmani/nanocoder that referenced this pull request Nov 16, 2026
Conflicts with on-demand MCP discovery (Nano-Collective#1651, Nano-Collective#2052, Nano-Collective#2057):
- tool-manager.ts: kept discovery, the catalog and outage recovery, with
  this branch's registration rule on every path. A name a built-in,
  custom or skill tool has is skipped from the catalog too, so
  load_tool_schema can't offer the MCP schema for it, and loadMcpTool
  won't claim it. Tools loaded on demand are tracked, so an outage or a
  disconnect removes them and never the built-in.
- daemon/entry.ts, plain/initialize.ts: pass upstream's tune config and
  keep the skipped-tools warning.
- Specs: kept both sides; setGlobalMessageQueue moved to
  @/components/message-queue (Nano-Collective#2155), and the custom-tools stand-in
  client now maps its tool, which initializeMCP reads.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agent:needs-work nc-review found blocking findings area:docs Documentation area:tools Tool implementations and tool-calling area:tui Terminal UI

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Feature] Architecture: On-demand MCP Tool Discovery to preserve local context windows

3 participants