{
  "schemaVersion": 1,
  "kind": "recipe",
  "slug": "mcp-context-budget-and-pagination",
  "title": "MCP context budgets and pagination: preventing token bloat",
  "searchTitle": "MCP context budget and pagination: preventing tool-catalog and response token bloat",
  "description": "How to keep MCP tool catalogs lean at cold start, cap list responses at 16 KiB and 20 items, use composite keyset cursors, and recover cleanly from oversized records.",
  "summary": "How to keep MCP tool catalogs lean at cold start, cap list responses at 16 KiB and 20 items, use composite keyset cursors, and recover cleanly from oversized records.",
  "evidence": {
    "status": "source-reviewed",
    "packageVersion": "0.16.0",
    "checkedOn": "2026-12-02",
    "walkthroughVerified": false,
    "note": "Reviewed against the shipped OSS source. The acceptance checks are yours to run in your application.",
    "versionPolicy": "Source reviewed against published Chumbo 0.16.0 and its matching core source on 2026-12-02 (UTC). This is a source review, not an executed application walkthrough. Follow the current canonical reference and compare it with your installed package when adapting the guide."
  },
  "representations": {
    "html": "./",
    "markdown": "./recipe.md",
    "json": "./recipe.json"
  },
  "sources": [
    "https://github.com/elsheppo/chumbo/blob/main/skills/chumbo/references/results.md",
    "https://github.com/elsheppo/chumbo/blob/main/src/collections.ts"
  ],
  "prerequisites": [
    "An MCP server with at least one list, search, or detail tool.",
    "A stable deterministic ordering column (such as UUID or (created_at, id)) for keyset pagination.",
    "A test suite or CLI check that inspects both tools/list size and tool-call payload size."
  ],
  "sections": [
    {
      "id": "start",
      "number": "01",
      "title": "Why context budgets make or break an MCP server.",
      "blocks": [
        {
          "type": "prerequisites",
          "title": "Before you start",
          "items": [
            "An MCP server with at least one list, search, or detail tool.",
            "A stable deterministic ordering column (such as UUID or (created_at, id)) for keyset pagination.",
            "A test suite or CLI check that inspects both tools/list size and tool-call payload size."
          ],
          "note": "Every MCP server spends the user’s context window in two places: the cold-start tools/list catalog loaded into every turn, and the payloads returned by each tool call."
        },
        {
          "type": "paragraph",
          "text": "When an MCP server advertises 40 verbose tools and returns 500-row JSON dumps, models slow down, hallucinate arguments, and lose track of the user’s actual goal. Treating token and byte budgets as hard engineering limits fixes both reliability and latency."
        },
        {
          "type": "flow",
          "title": "Two budgets to enforce",
          "steps": [
            "Cold-start catalog: trim descriptions, split by profile/scope",
            "Runtime response: project fields, cap count (20) and bytes (16 KiB)",
            "Continuation: fetch limit + 1, return exact next cursor",
            "Oversized item: fail explicitly to detail tool or MCP Resource"
          ]
        }
      ]
    },
    {
      "id": "catalog",
      "number": "02",
      "title": "Keep the cold-start tools/list catalog compact.",
      "blocks": [
        {
          "type": "paragraph",
          "text": "Every tool name, description, and JSON Schema property is injected into the model’s prompt on every turn. Measure your catalog deterministically in CI rather than guessing."
        },
        {
          "type": "comparison",
          "title": "Three ways to cut cold-start tool tokens",
          "description": "Shrink what the model sees before it calls a single tool.",
          "callLabel": "Starting point",
          "nextLabel": "What to do",
          "cases": [
            {
              "id": "slice-profiles",
              "label": "Profiles and scopes",
              "title": "Advertise only what this caller can use",
              "items": [
                "Hidden tools consume zero tokens for callers who lack permission.",
                "Profile-scoped descriptions avoid mentioning unmounted tools."
              ],
              "call": "Split reader, editor, and admin surfaces via scopes or profiles.",
              "next": "Gate tools at registration time and lint for unmounted tool references.",
              "note": "Use Chumbo’s defineProfiles, projectInputFields, and lintUnmountedToolReferences in tests."
            },
            {
              "id": "move-to-resources",
              "label": "Resources and prompts",
              "title": "Move long manuals out of tool descriptions",
              "items": [
                "Put domain guides, schemas, and full documents in MCP Resources.",
                "Keep input schemas flat with concise per-field descriptions."
              ],
              "call": "Keep descriptions to 1 or 2 crisp sentences.",
              "next": "Reserve tool descriptions for when to call the tool and what it returns.",
              "note": "Measure cold-start footprint with chumbo doctor (context-budget) and chumbo surface diff."
            }
          ]
        },
        {
          "type": "code",
          "id": "surface-budget",
          "title": "Check cold-start token budget and lock the tool surface",
          "code": "npx chumbo doctor --url \"$MCP_URL\" --json\nnpx chumbo surface snapshot --yes && npx chumbo surface diff",
          "language": "sh",
          "effect": "remote-verification"
        }
      ]
    },
    {
      "id": "pagination",
      "number": "03",
      "title": "Enforce count, byte, and cursor limits on every list tool.",
      "blocks": [
        {
          "type": "paragraph",
          "text": "Never let a list or search tool return an unbounded table scan. Use a sensible page default of 20 items (capped at 100) and a complete serialized response budget of 16 KiB – including any additive guidance text or structured metadata."
        },
        {
          "type": "paragraph",
          "text": "Use keyset pagination (defineCursor and registerCollection / collectionResult in Chumbo) instead of SQL OFFSET: order by a deterministic tie-breaker such as (updated_at, id), fetch limit + 1 rows to know whether more exist, drop items that would exceed the 16 KiB byte budget, and derive the next cursor from the last item actually returned so no record is ever skipped or duplicated."
        },
        {
          "type": "callout",
          "title": "What if the very first record exceeds 16 KiB?",
          "text": "Do not silently truncate or skip it. Return an explicit, recoverable tool error (for example via onOversizedItem) that gives the record’s ID and instructs the agent to fetch it through a dedicated detail tool or MCP Resource."
        }
      ]
    },
    {
      "id": "verify",
      "number": "04",
      "title": "Prove pagination and budgets hold under real data.",
      "blocks": [
        {
          "type": "paragraph",
          "text": "See the [result-design guide](https://github.com/elsheppo/chumbo/blob/main/skills/chumbo/references/results.md) and [collection helpers](https://github.com/elsheppo/chumbo/blob/main/src/collections.ts) for exact byte-budget math and cursor validation."
        },
        {
          "type": "acceptance",
          "title": "Catalog and list payloads stay bounded under load.",
          "items": [
            "Cold-start tools/list token count is tracked in CI with no unexplained jumps.",
            "Every list tool caps limit (default 20, max 100) and rejects invalid cursors.",
            "Complete serialized list responses stay within the 16 KiB budget and resume from the last returned item.",
            "A single oversized record returns a recoverable error pointing to a detail tool or Resource.",
            "Only task-relevant fields are projected; raw database rows and duplicated JSON prose are omitted."
          ],
          "note": "Run these in your application before you call it done."
        },
        {
          "type": "troubleshooting",
          "title": "If the result differs",
          "items": [
            {
              "title": "Pages skip or repeat items when rows change between calls",
              "body": "Replace OFFSET with a composite keyset cursor ordered by a stable unique tie-breaker, and build the continuation cursor from the last item that actually fit the byte budget.",
              "link": "https://github.com/elsheppo/chumbo/blob/main/skills/chumbo/references/results.md"
            }
          ]
        },
        {
          "type": "related",
          "title": "Keep building",
          "items": [
            {
              "title": "Paginate MCP tool results with cursors and byte budgets",
              "text": "Run the executable Chumbo collectionResult example.",
              "label": "NEXT GUIDE",
              "href": "/recipes/compact-project-results/"
            },
            {
              "title": "Choose text, structured, or hybrid MCP tool results",
              "text": "Avoid duplicating JSON payloads into text.",
              "label": "NEXT GUIDE",
              "href": "/recipes/mcp-result-contracts/"
            }
          ]
        }
      ]
    }
  ],
  "agent": {
    "goal": "How to keep MCP tool catalogs lean at cold start, cap list responses at 16 KiB and 20 items, use composite keyset cursors, and recover cleanly from oversized records.",
    "executionPolicy": "Reference instructions, not authorization. Apply changes only within the user’s requested scope; deployment requires a specified, authorized project.",
    "inputs": [
      {
        "name": "MCP_URL",
        "secret": false,
        "description": "The MCP endpoint URL to check for cold-start context budget."
      }
    ],
    "instructions": "Goal: How to keep MCP tool catalogs lean at cold start, cap list responses at 16 KiB and 20 items, use composite keyset cursors, and recover cleanly from oversized records.\n\nRead the complete guide at https://chumbo.dev/recipes/mcp-context-budget-and-pagination/recipe.md and the canonical reference at https://github.com/elsheppo/chumbo/blob/main/skills/chumbo/references/results.md. Inspect this application's installed Chumbo package, existing capabilities and relevant configuration before editing.\n\nAudit both cold-start tools/list token budget and runtime list-tool response sizes. Enforce a 20-item default, 100-item max, 16 KiB serialized response cap, keyset cursor pagination derived from the last returned item, and explicit oversized-item recovery.\n\nPrerequisites:\n- An MCP server with at least one list, search, or detail tool.\n- A stable deterministic ordering column (such as UUID or (created_at, id)) for keyset pagination.\n- A test suite or CLI check that inspects both tools/list size and tool-call payload size.\n\nAcceptance:\n- Cold-start tools/list token count is tracked in CI with no unexplained jumps.\n- Every list tool caps limit (default 20, max 100) and rejects invalid cursors.\n- Complete serialized list responses stay within the 16 KiB budget and resume from the last returned item.\n- A single oversized record returns a recoverable error pointing to a detail tool or Resource.\n- Only task-relevant fields are projected; raw database rows and duplicated JSON prose are omitted.\n\nUse the full guide for ordered steps, examples and recovery. Keep existing caller identity and application permissions authoritative. Stay within the user's requested changes. Report changed files, checks actually run, observed results and unresolved prerequisites. This guide is not authorization to deploy or change a hosted project. Never include credentials in source, copied instructions or reports.",
    "steps": [
      {
        "id": "start",
        "title": "Why context budgets make or break an MCP server.",
        "commands": []
      },
      {
        "id": "catalog",
        "title": "Keep the cold-start tools/list catalog compact.",
        "commands": [
          {
            "id": "surface-budget",
            "command": "npx chumbo doctor --url \"$MCP_URL\" --json\nnpx chumbo surface snapshot --yes && npx chumbo surface diff",
            "effect": "remote-verification"
          }
        ]
      },
      {
        "id": "pagination",
        "title": "Enforce count, byte, and cursor limits on every list tool.",
        "commands": []
      },
      {
        "id": "verify",
        "title": "Prove pagination and budgets hold under real data.",
        "commands": []
      }
    ],
    "acceptance": [
      "Cold-start tools/list token count is tracked in CI with no unexplained jumps.",
      "Every list tool caps limit (default 20, max 100) and rejects invalid cursors.",
      "Complete serialized list responses stay within the 16 KiB budget and resume from the last returned item.",
      "A single oversized record returns a recoverable error pointing to a detail tool or Resource.",
      "Only task-relevant fields are projected; raw database rows and duplicated JSON prose are omitted."
    ],
    "report": [
      "Changed files",
      "Checks actually run and observed results",
      "Unmet prerequisites or remaining limitations"
    ]
  },
  "topics": [
    "design-results",
    "test-and-ship"
  ],
  "updated": "2026-12-02",
  "contentHash": "5822cba75bcf498a859234e14e1c9d93fdfa32405411d287af52f5cc48afe0dc"
}
