Content

Why Claude Code Guesses API Endpoints (and How to Stop It)

Why Claude Code invents API endpoints, parameters, and method names even with CLAUDE.md rules, what rules, docs, and hooks can and cannot fix, and how to make unknown or invalid API calls fail before they reach the provider.

Chaitrali Kakde

DevRel Engineer

AI AgentOct 7, 2026

Key takeaways

  • -Claude Code guesses API endpoints when it fills gaps from training data instead of reading your source code or the provider's current documentation.
  • -Public Claude Code issues show guessed endpoints, invented field names, and a CRM where about 917 deals got the wrong owner after the agent guessed query parameters.
  • -CLAUDE.md rules are instructions the model weighs against everything else in context. They lower the guess rate but do not enforce anything.
  • -A PreToolUse hook can block a tool call with exit code 2, but it cannot confirm the agent read the right file or used the right schema.
  • -Research on tool calls finds most wrong calls are well-formed but carry wrong values, so a JSON shape check alone does not catch them.
  • -Swytchcode makes Claude Code look up an operation in a catalog, read its schema, and run it through a step that rejects unknown operations and invalid inputs before any request is sent.

Claude Code guesses API endpoints when it writes or runs a call from patterns in its training data instead of from your code or the provider's current documentation. The guess usually looks right: a plausible path, a sensible parameter name, a method that sounds like it should exist. Rules in CLAUDE.md lower how often this happens but cannot prevent it, because the model treats them as instructions to weigh, and nothing checks the call before it runs. The reliable fix is to give Claude Code a catalog of real API operations to look up, and an execution step that refuses any call that is not in the catalog or does not match the schema.

This article covers what guessing looks like, documented cases from the Claude Code issue tracker, why it keeps happening with strong models and strict rules, which fixes help and where each one stops, and how to set up Claude Code so a guessed call fails before it reaches the API. For the general version of this problem across all agents, see the guide on why AI agents call the wrong API linked at the end. Checked against the Claude Code documentation and public GitHub issues in October 2026.

What does it look like when Claude Code guesses an API?

Guesses fall into a few repeatable patterns:

  • Endpoint paths. Trying /jobs?workspaceId=X, then /workspaces/{id}/jobs, then a different base URL, instead of reading the route the project already defines.
  • Query parameters. Passing a filter the API ignores or interprets differently, so the call succeeds and returns or changes the wrong records.
  • Request body fields. Sending fields the endpoint does not accept, leaving out required ones, or nesting them in the wrong place.
  • Deprecated SDK methods. Writing an older call that still appears in tutorials, such as stripe.charges.create where Stripe now recommends PaymentIntents.
  • Identifiers in your own code. Column names, config keys, and function names that sound right but do not exist in the project.

Documented cases from the Claude Code issue tracker

These come from public issues on the anthropics/claude-code GitHub repository. Each was filed by a user describing their own session.

  • Issue #61931, endpoint guessing despite a CRITICAL rule. In a long session on Opus 4.7 with a 1M-token context, Claude Code tried several URL patterns and direct cloud function invocations instead of reading the test helpers that already defined the route and headers. The project's CLAUDE.md said "NEVER guess API endpoint paths, ID formats, or response shapes" and the user's memory files repeated it. The rule was broken four or more times in one task.
  • Issue #53988, invented identifiers and API contracts. Claude wrote column names, model fields, and config keys from memory. In one case, the backend expected {refresh_token} in the request body for logout and refresh, the frontend Claude wrote sent an empty body, and both endpoints returned 422 at runtime.
  • Issue #50180, guessed parameters on production data. An agent updating a law firm's Pipedrive CRM guessed query parameter values instead of reading the API reference. About 917 deals ended up with the wrong owner. The reporter noted that the docs would have shown a known issue where a v1 filter is silently ignored. The issue was closed as a duplicate of an earlier report, which suggests the pattern is not rare.

Gemini CLI, Cursor, and GitHub Copilot users report the same class of problem. Claude Code is a useful example because its users document sessions in detail and its configuration (CLAUDE.md, hooks, and MCP) gives several places to intervene.

Why Claude Code guesses even with CLAUDE.md rules

  • The model predicts plausible code. A name like getUserByEmail or a path like /workspaces/{id}/jobs fits millions of codebases. Without evidence in context, the most likely-looking answer wins.
  • Training data mixes API versions. Old tutorials, forum answers, and current docs all teach slightly different versions of the same API.
  • Rules compete with everything else in context. In a long session, CLAUDE.md is one input among many thousands of tokens of code, logs, and conversation. After compaction, the summary may keep the task and lose the emphasis.
  • Trying is cheaper than reading, until it is not. For a read, guessing a few URLs costs seconds. For a write, the first wrong guess can change real data.
  • Rules describe behavior without checking it. A comment on issue #61931 points out the structural gap: "read the handler source before guessing endpoints" is a positive obligation, and a PreToolUse hook cannot deterministically check from the next tool call alone whether the agent read the right file.

Research points the same way. The ParamBench study (arXiv 2608.03071, 2026) audited failed tool calls from seven frontier models and found that only 2.1% violated the schema. The rest were well-formed calls with wrong values. In the authors' tests, Claude Opus 4.7 filled only 33.4% of calls correctly on the NESTFUL benchmark. A check that only asks whether the JSON fits the schema misses most real mistakes. Catching them takes the real schema for the exact operation, plus guardrails such as dry runs and approvals for writes.

Fixes that reduce guessing, and where each one stops

FixWhat it helps withWhere it stops
CLAUDE.md rule such as "read the handler before calling an API"Sets the expectation in every sessionAdvisory. The model can still skip it, especially in long sessions
Exact signatures or an OpenAPI excerpt pasted into the promptCorrect names and shapes for that taskGoes stale when the API changes and uses context on every task
Documentation MCP server, such as Context7Current, version-specific docs on demandThe model still decides whether to look, and nothing stops the call if it does not
PreToolUse hook that exits with code 2Blocks known-bad commands, such as raw curl to a production APISees only the next tool call. Cannot confirm what the agent read, and you write the logic per API
Type checks and testsInvented identifiers inside your codebaseDo not cover HTTP calls the agent runs from the shell or JSON bodies sent to third-party APIs
Execution layer with an operation catalogUnknown operations and invalid inputs are rejected before the request is sentCovers APIs in the catalog or added from an OpenAPI spec. Does not check names in your own code

These layer well. Rules and docs make a good first attempt more likely. Hooks block the worst commands. Tests catch mistakes in your code. An execution layer makes the external API call itself fail closed when the operation or inputs are wrong.

A CLAUDE.md section that helps

Keep the rule short and specific, name the tools to use, and say what to do when a check fails. General warnings such as "be careful with APIs" do little.

## External APIs

- Never write an API path, parameter, or request body from memory.
- For internal endpoints, read the route handler or the test helper that calls it first.
- For third-party APIs, use the Swytchcode MCP tools: discover the operation,
  read its schema with info, then exec. Use dry_run=true before any write.
- If exec returns a validation or policy error, show it to me and stop.
  Do not try other endpoints or providers to work around it.

A PreToolUse hook that blocks raw calls to vendor APIs

Claude Code runs PreToolUse hooks before a tool call executes. If the hook exits with code 2, the call is blocked and the text written to stderr is fed back to Claude as the reason. This example blocks curl commands to a few production API hosts so the agent has to use the governed path. Adjust the host list for your stack.

// .claude/settings.json
{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Bash",
        "hooks": [
          { "type": "command", "command": ".claude/hooks/block-raw-api.sh" }
        ]
      }
    ]
  }
}
#!/usr/bin/env bash
# .claude/hooks/block-raw-api.sh
# Claude Code passes the tool call as JSON on stdin.
cmd=$(jq -r '.tool_input.command // ""')

if echo "$cmd" | grep -Eq 'curl[^|]*https://api\.(stripe|github|pipedrive)\.com'; then
  echo "Raw calls to vendor APIs are blocked. Use Swytchcode discover, info, and exec instead." >&2
  exit 2
fi
exit 0

Treat the hook as a fence. It closes one route around the governed path, and it cannot tell whether the next call Claude makes is correct.

How Swytchcode stops Claude Code from guessing API calls

Swytchcode is an execution layer between your agents and the APIs they call. Claude Code describes the job in plain language, Swytchcode returns real operations from its catalog, and every call runs through the same pipeline: resolve the tool, validate inputs, evaluate policies, resolve credentials, execute, and normalize the response. A guessed operation or a malformed payload fails at validation, before any request leaves your machine.

Set it up from the project root. With the claude editor option, swy init writes Swytchcode guidance into CLAUDE.md and registers the MCP server through claude mcp add, so Claude Code writes the entry to the config file it actually reads.

# Install the CLI, then initialize the project for Claude Code in sandbox mode
npm install -g swytchcode
swy init --editor=claude --mode=sandbox

# Check the setup
swy doctor

From then on, Claude Code follows this loop. The canonical ID comes from discover, never from memory.

# 1. Find the operation by describing the job
swy discover "update the owner of a CRM deal" --json

# 2. Fetch the integration, enable the operation, and read its real input schema
swy get <project>
swy add <canonical_id>
swy info <canonical_id>

# 3. Run it (inputs as CLI arguments or JSON on stdin)
swy exec <canonical_id>

Over MCP, Claude Code uses the same steps as tools: discover, info, and exec, with dry_run=true to preview a call without sending it.

What happens when Claude Code guesses anyway:

  • Unknown operation. A canonical ID that is not enabled in tooling.json does not run. The CLI exits with code 2.
  • Invalid inputs. Missing required fields, wrong types, or fields the schema does not define fail validation and exit with code 1. No request is sent.
  • Provider errors. If the provider rejects the call, the result includes the status code, an error category, and whether it is retryable, so Claude Code can correct the input instead of trying random endpoints. A 200 response with an error in the body is treated as a failure.
  • Changed APIs. swy sync re-downloads installed integrations and warns when an enabled operation's definition has changed, so a drifted schema shows up as a warning instead of a runtime surprise.

For writes against production data, add policies. Allow and deny rules (Pro plan and above) can block bulk updates or restrict which operations run in production, and approval rules (Business and Enterprise) hold a call until a person approves it in Slack or Telegram. In a case like the CRM incident above, a dry run plus an approval rule on bulk owner changes would have put a person in front of the first wrong update.

Where this does not help

Swytchcode governs calls to external APIs and to internal APIs you describe with an OpenAPI spec. It does not check column names, config keys, or function names inside your own code, which made up most of issue #53988. For those, rely on type checking, tests, and reading the source. It also cannot know an API's undocumented quirks, such as a filter the provider silently ignores. Dry runs, approvals, and starting in sandbox mode limit the damage when that happens.

FAQ

Why does Claude Code ignore my CLAUDE.md rules?
Claude Code weighs CLAUDE.md against everything else in context. In long sessions it competes with large amounts of code and conversation. Short, specific rules that name a tool to use hold up better than general warnings, but no rule is enforced.

Can a Claude Code hook stop it from guessing API endpoints?
A PreToolUse hook can block specific commands by exiting with code 2, such as curl requests to production API hosts. It cannot confirm that the agent read the right file or that its next call is correct, so use hooks as a fence around a governed path.

Does giving Claude Code the API docs fix hallucinated endpoints?
It helps when the model reads them. A documentation MCP server or a pasted reference improves the first attempt, but nothing stops a call that skips or misreads the docs. Validation against the real schema at execution time covers that gap.

Is this only a problem with one Claude model?
No. The issues above involve Opus 4.7, and similar reports exist for Gemini CLI, Cursor, and GitHub Copilot. ParamBench found the same pattern across seven frontier models: most failed tool calls were well-formed but had wrong values.

Does Swytchcode work with Claude Code?
Yes. Run swy init --editor=claude to register the Swytchcode MCP server and add guidance to CLAUDE.md, or start the server directly with swy mcp serve --claude. Claude Code can also call the swytchcode CLI as a shell command.

Swytchcode resources

More content