Join our Newsletter — 33% off our NHI Course
Home› Guides› Exposing Existing APIs as MCP Tools: OpenAPI Conversion…
Guide MCP, Protocols & Agent Platforms

Exposing Existing APIs as MCP Tools: OpenAPI Conversion Risks and Safe Patterns

PDF for newsletter subscribers · free to read online

← All guides
By NHI Mgmt Group, edited by Lalit Choda Updated 14 November 2026 17 min read
On this page

Converting an OpenAPI description into MCP tools takes minutes, and the security review that should go with it usually takes none. Generators, gateways and SDK helpers can now turn every operation in a spec into a model-callable tool, carry over whatever credential the HTTP client holds, and paste developer-facing descriptions straight into the model's context. This guide covers only the conversion step: the four risks that appear when tools are generated from an existing API (operation over-exposure, credential passthrough, poor descriptions and loose tool scoping), how each converter behaves by default, and a review pipeline that makes generated tools safe to ship. For the broader choice between generated and hand-built tools, see the MCP vs OpenAPI Tool Definitions; for designing the underlying API for agents, see API Design for AI Agent Consumers.

Key takeaways

  • The default is "everything". FastMCP's default route map turns every endpoint into a tool, and Azure API Management lets an administrator select all operations in one click; an allowlist has to be configured deliberately.
  • The converter decides which identity acts. Generated tools normally share one HTTP client and one credential, so the narrowest operation runs with the broadest permission in the spec, and the MCP specification forbids the shortcut of forwarding the caller's token downstream.
  • Spec text becomes prompt text. Summaries, descriptions, parameter descriptions and examples written for developers flow into the model unchanged, so a stale or hostile description steers tool selection and arguments.
  • Scope the tool set, not just the token. Fewer, task-shaped tools with strict input schemas and accurate annotations reduce both misuse and model confusion; annotations are hints and never a security control.
  • Treat conversion as a build step with a gate. Lint the spec, generate, diff the tool catalogue against the approved baseline and fail the build when a new write operation or changed description appears without review.

How conversion works and where the risk enters

Every converter performs the same four transformations, whatever the product. Each one is a point where a security decision is made, usually by a default rather than a person.

TransformationWhat the converter doesDecision hidden in the defaultRisk if left unreviewed
Operation selectionReads paths and methods and decides which become tools, resources or nothingWhich operations the model can callOperation over-exposure (admin, delete, bulk export)
NamingDerives a tool name, usually from operationId, summary or method plus pathHow the model distinguishes similar operationsTool confusion, wrong operation chosen
Description and schema mappingCopies summary, description, parameters and request body schema into description and inputSchemaWhat the model is told and what arguments are acceptedPoor or injected descriptions, permissive inputs
Request executionBuilds the HTTP request with a configured client, base URL and headersWhich credential and which network path every call usesCredential passthrough, shared over-privileged identity, SSRF via base URL

Converters come in three shapes: libraries that build an MCP server in your code (FastMCP's from_openapi() is a widely documented example), API gateways that publish operations of a managed API as an MCP endpoint (Azure API Management's MCP server feature, for example), and hosted connector services that ingest a spec and serve tools.

Risk 1: operation over-exposure

An OpenAPI description is meant to be complete. Internal specs routinely include user administration, feature flags, bulk export, reindexing, debug endpoints and permanent deletes alongside the three read operations an agent actually needs. A one-to-one conversion turns all of them into actions the model can choose, which is the "excessive functionality" form of OWASP LLM06:2025 Excessive Agency, and it multiplies the impact of any server-side gap in API5:2023 Broken Function Level Authorization.

What the defaults do

  • FastMCP: the documented default route map is a single RouteMap(mcp_type=MCPType.TOOL), so every endpoint becomes a tool. Custom route maps are checked in order and the first full match wins, and the defaults still apply after your maps. Ending the list with a catch-all RouteMap(mcp_type=MCPType.EXCLUDE) turns the list into an allowlist, because nothing falls through to the default.
  • Azure API Management: when creating an MCP server from a managed REST API, the administrator selects one or more operations, or all of them, and can change the exposed set later in the server's Tools blade.
  • Any converter: regeneration in CI silently picks up new operations as the API evolves.

Controls

  1. Classify every operation before converting. Tag each operation in the spec as read, write, destructive, external-send or administrative. A vendor extension such as x-agent-exposure: allow on approved operations gives the converter something explicit to match; extensions are permitted by the OpenAPI specification and ignored by tools that do not understand them.
  2. Allowlist, never denylist. Match approved operations by operationId or by tag and exclude everything else.
  3. Keep destructive operations out of the generated set. If the agent must delete or pay, wrap that single operation in a hand-written tool that adds confirmation, dry run and server-side checks.
  4. Split by audience. Generate separate MCP servers, or separate gateway products, per agent role rather than one server for every agent. A support agent and a finance agent should never discover each other's tools in tools/list.
  5. Budget the tool count. Set a ceiling per server (for example 15 to 20 tools) and treat breaching it as a design review trigger. Large catalogues increase wrong-tool selection, and FastMCP's own documentation states that LLMs perform significantly better with curated servers than with auto-converted OpenAPI servers, especially for complex APIs.

Risk 2: credential passthrough and the shared identity

Credential handling is where conversion does the most damage quietly. Two opposite anti-patterns are common, and both appear in generated servers.

  • One static credential for every tool: FastMCP documents setting authentication on the HTTP client, for example an Authorization: Bearer header on the client passed to from_openapi(), and configured headers are sent with each request. The downstream API cannot tell which user or agent caused a call, and the credential's scope is the union of everything any tool might need.
  • Forwarding the caller's token downstream: the MCP security best practices describe "token passthrough" as an anti-pattern in which an MCP server accepts tokens from a client without validating that they were issued to the MCP server and passes them to the downstream API. It is explicitly forbidden by the authorisation specification: MCP servers MUST NOT accept tokens that were not issued for them.

Converters handle headers differently, so check rather than assume. FastMCP's documentation states that over HTTP, incoming MCP request headers are forwarded to the API except Authorization, Cookie and Host, and only fill headers the outgoing request does not already set. That protects the bearer token, but other incoming headers (tenant IDs, API keys sent in custom headers, trace headers) can still reach the backend unless you strip them. Azure API Management's troubleshooting guidance notes that a backend returning 401 usually means the Authorization header was not forwarded, and suggests a set-header policy; before doing that, decide which token belongs on that hop.

PatternWho the backend seesBlast radiusWhen it is acceptable
Shared static API key on the clientOne service identity for all usersUnion of every generated tool's needsRead-only, non-sensitive internal data, single-tenant prototypes
Caller's token forwarded unchangedThe user, with a token never meant for this APIAnything the token's audience allows, plus loss of auditNever: forbidden by the MCP authorisation specification
Dedicated workload identity per server, scoped to allowlisted operationsThe agent service, consistentlyOnly the approved operationsAutonomous back-office agents with no user context
Token exchange to a downstream token bound to the API audienceThe user, with the agent recorded as actorThe user's rights, narrowed to the requested scopeUser-facing agents acting on behalf of a person

For user-facing agents the pattern to aim for is token exchange: validate the inbound token's audience at the MCP server, then obtain a separate token for the downstream API with only the scopes the selected tool needs. The OAuth Token Exchange vs Token Passthrough guide covers the mechanics. Map each OpenAPI operation's security requirement (the scopes listed under security) into the tool's scope so that a write tool triggers a scope step-up rather than inheriting a broad token at session start; the MCP best practices recommend a minimal initial scope set and incremental elevation through targeted WWW-Authenticate scope challenges, and list publishing every scope in scopes_supported as a common mistake.

Where the generated server is itself an OAuth client to a third-party API, the confused deputy conditions in the MCP best practices apply: a static client ID, dynamic client registration and a consent cookie at the third-party authorisation server. Proxy servers MUST implement per-client consent before forwarding to third-party authorisation. See the Confused Deputy in AI Agents Guide.

Risk 3: poor and untrusted descriptions

The MCP tool schema describes description as a hint to the model about what a tool does. In a generated server that hint is whatever developers wrote for documentation, often years ago, sometimes merged from several teams or pulled from a partner's spec at build time.

  • Misleading or missing descriptions: a summary of "Update record" on an operation that also deletes child records leads the model to call it casually.
  • Ambiguous names: FastMCP derives the tool name from the operationId up to the first double underscore, falls back to the summary, then to method and path, slugifies the result, truncates it to 56 characters and appends a number to keep names unique. Names such as update_item_2 and update_item_3 are a reliable source of wrong-tool calls. The MCP specification recommends tool names of 1 to 128 characters using letters, digits, underscore, hyphen and dot, unique within a server.
  • Injected instructions: anyone who can edit the spec, a code annotation that generates it, or an upstream partner spec can place instructions in a description, parameter description or example that the model will read on every session. The MCP Tool Poisoning Detection guide covers detection of this class.

Rewrite rules for model-facing text

  1. Override names explicitly. FastMCP accepts an mcp_names map from operationId to tool name; name by effect and object, for example invoice_get_by_id or ticket_close_permanently.
  2. Replace descriptions rather than appending to them. FastMCP's mcp_component_fn lets you modify each generated component in place, including its description; keep the replacement text in a reviewed file in the repository, not in the spec.
  3. State side effects, required approvals and what the tool must not be used for in one or two plain sentences. Strip Markdown, HTML, links and example payloads from model-facing text.
  4. Tighten the input schema: enums for status fields, maximum lengths, formats, and additionalProperties: false. FastMCP drops unknown tool arguments with a warning by default; turn on its strict input validation so that malformed calls fail instead.
  5. Add an output schema and return only the fields the task needs. The MCP specification requires servers that declare an outputSchema to return conforming structured results, which gives you a natural point to trim free-text fields that may carry indirect prompt injection (ATLAS AML.T0051.001).
  6. Hash each approved definition (name, description, input schema, annotations) and alert when the hash changes outside a reviewed release.

Risk 4: loose tool scoping and annotations

Tool scoping is the sum of three things: which tools a caller can discover, which they can call, and what each tool can reach. Generated servers tend to get all three wrong at once because the converter has no notion of the caller.

  • Discovery: filter tools/list per caller so that an agent only sees tools its role may use.
  • Invocation: enforce authorisation on every tools/call at the server or gateway, and again at the API. The MCP tools specification says servers MUST validate all tool inputs, implement proper access controls, rate limit tool invocations and sanitise tool outputs.
  • Reach: pin the base URL. FastMCP builds a default client from the first server URL in the spec if you do not pass one; pass your own client with a fixed base URL and timeout so a modified servers entry cannot redirect traffic. Operations that accept URLs as parameters need an allowlist and an egress proxy.
  • Errors: FastMCP's mask_error_details=True hides upstream status and reason detail from callers; use it in production so backend error text does not leak internals into the model context.

Generated tools should also carry accurate annotations. The MCP schema defines readOnlyHint (default false), destructiveHint (default true, meaningful only when not read-only), idempotentHint (default false) and openWorldHint (default true). Derive them from the HTTP method and your operation classification: GET operations marked read-only, DELETE and purge operations marked destructive, PUT marked idempotent where it truly is. The schema is explicit that annotations are hints and that clients should never make tool use decisions based on annotations from untrusted servers, so they help well-behaved hosts present confirmations but never replace server-side checks.

Operation classExpose by generation?Annotations to setExtra control
Read, single objectYes, if on the allowlistreadOnlyHint trueObject-level authorisation at the API (API1:2023)
Read, list or searchYes, with bounded page sizereadOnlyHint trueOutput field allowlist, result cap
Bulk exportNoNot applicableSeparate reviewed tool with volume limits
Create or updateOnly with an allowlist and strict schemareadOnlyHint false, destructiveHint false, idempotentHint as true for real PUT semanticsIdempotency keys, per-user rate limits
Delete, purge, payment, sendNo: hand-written wrapperdestructiveHint trueConfirmation, dry run, human approval (ATLAS AML.M0029)
Administrative (users, roles, keys, config)NoNot applicableKeep outside agent reach entirely

Gateway-based conversion: what changes

A gateway puts conversion behind a console, which helps governance but can hide the same defaults. On Azure API Management, for example:

  • Policies apply to every exposed tool: policies configured on the MCP server apply to all operations exposed as tools, with global policies evaluated first. Per-tool differences (stricter limits on a write tool) need conditions in policy or separate MCP servers.
  • Rate limiting and tracing: the documented example applies rate-limit-by-key and records an agent-id header in a trace, a useful baseline for attributing tool calls to agents.
  • Logging: the documentation advises setting the number of frontend response payload bytes to log to 0 when diagnostic logging is enabled globally, to avoid unintended logging of response bodies, and warns against reading context.Response.Body in MCP server policies because it breaks streaming.
  • Access: associating the MCP server with a product lets you manage access and subscriptions through that product. A subscription key identifies a consumer application, not a user, so pair it with OAuth where tools act for people.

See the MCP Gateway and MCP Server Governance Guide.

Where identity fits

A generated MCP server is a new non-human identity even when nobody registers it as one. It holds a credential, calls production APIs and acts at machine speed for many users. Give it an owner, an inventory record and its own credential, scoped to the allowlisted operations and rotated on a schedule; never reuse a developer's personal token or a CI token because it "already works". The API Keys vs OAuth for MCP Servers guide covers the credential choice.

How to implement: a conversion review pipeline

  1. Lint the spec. Require an operationId, summary and security requirement on every operation, and an exposure classification extension on any operation intended for agents. Fail on missing fields before conversion starts.
  2. Generate into a staging server. Configure the converter with an explicit allowlist (catch-all exclude rule, or explicit gateway selection), name overrides and a fixed HTTP client. Do not point it at production credentials yet.
  3. Export and diff the catalogue. Call tools/list on the staging server and save the result as a reviewed artefact. In CI, compare each build with the approved baseline and fail on any new tool, removed tool, changed description, changed schema or changed annotation.
  4. Review model-facing text. A named reviewer approves each description and schema as prompt text, using the rewrite rules above.
  5. Bind the credential. Issue the server's own identity or configure token exchange; confirm that no inbound token is forwarded unchanged and that unexpected inbound headers are stripped.
  6. Test misuse, then release to one agent role first. In a pilot, attempt calls outside the allowlist, malformed arguments, oversized results and instructions planted in test data, and confirm each is blocked or contained. The MCP Security Testing Guide covers test design.
  7. Roll back by catalogue version. Keep the previous approved catalogue and credential configuration deployable; reverting the tool set is faster and safer than editing a live server.

Detection and measurement

Log every tools/call with tool name, caller identity, agent identifier, arguments (redacted where sensitive), downstream operation and result status, and correlate with the API's own access logs.

  • Exposure ratio: tools exposed divided by operations in the spec. A ratio near 1 for a large spec means the allowlist is not doing its job.
  • Write share: percentage of exposed tools that are not read-only. Track it per server and require sign-off when it rises.
  • Unreviewed drift events: builds where the catalogue changed without approval. The target is zero merged.
  • Shared credential coverage: number of generated servers still using a shared static credential across all tools.
  • Denied tool calls: calls rejected by server or gateway authorisation, by tool and agent. A spike points to an over-broad discovery list or an injection attempt.

Common failure patterns

  • Selecting all operations to get a demo working, then shipping the demo. The fix is an allowlist from day one, even for prototypes.
  • A broad platform token on the generated client. The PocketOS Database Deletion 2026 shows the outcome when an agent holds an account-scoped token created for a narrow job and finds a delete operation that runs immediately with no undo.
  • Forwarding the user's Authorization header to the backend to fix a 401, which turns the server into a token passthrough proxy.
  • Regenerating in CI without a catalogue diff, so new admin endpoints appear as tools after an unrelated API release.
  • Trusting annotations as controls, for example relying on destructiveHint to trigger confirmation when some hosts ignore it.

Framework mapping

Control areaNIST SP 800-53 Rev 5NIST CSF 2.0OWASP and MITRE ATLAS
Operation allowlist and tool count budgetAC-6 Least Privilege, CM-8 System Component InventoryPR.AA-05LLM06:2025 Excessive Agency, API5:2023 Broken Function Level Authorization
Per-call authorisation and object checksAC-3 Access EnforcementPR.AA-05API1:2023, AML.T0053 AI Agent Tool Invocation
No token passthrough, dedicated server identityIA-5 Authenticator Management, IA-9 Service Identification and AuthenticationPR.AA-05API2:2023 Broken Authentication, AML.T0098 AI Agent Tool Credential Harvesting
Description review, strict schemasSI-10 Information Input ValidationPR.PS-01AML.T0051 LLM Prompt Injection
Catalogue diff and change controlCM-3 Configuration Change ControlPR.PS-01LLM06:2025
Tool call loggingAU-2 Event Logging, AU-12 Audit Record GenerationDE.CM-09AML.T0086 Exfiltration via AI Agent Tool Invocation
Human approval for destructive toolsAC-6PR.AA-05AML.M0029 Human In-the-Loop for AI Agent Actions

Practitioner checklist

  • Classify every operation in the spec before conversion and mark approved ones explicitly.
  • Configure the converter as an allowlist (catch-all exclude or explicit gateway selection); never "all operations".
  • Keep delete, payment, send and administrative operations out of generated tools; wrap any that are needed by hand.
  • Give the generated server its own credential scoped to the allowlisted operations, or use token exchange for user-facing agents.
  • Confirm no inbound token is forwarded unchanged and strip unexpected inbound headers.
  • Override tool names and replace descriptions with reviewed, plain, side-effect-stating text.
  • Turn on strict input validation, add output schemas and mask upstream error details.
  • Set accurate annotations, and enforce the same intent server-side.
  • Diff the tools/list catalogue in CI and fail builds on unreviewed changes.
  • Track exposure ratio, write share and drift events per server.

Standards and references

Related NHI Mgmt Group resources: MCP vs OpenAPI Tool Definitions · OpenAPI Specification Security Guide · API Design for AI Agent Consumers · MCP Security Guide · OWASP LLM Top 10 LLM06 Excessive Agency Guide

PDF for subscribers

Take this guide with you

Every section, table and checklist in one PDF, with links to the sources and related guides. Subscribe to our weekly NHI & AI Identity Journal and we’ll email you a download link.

Free weekly newsletter

Subscribe to the NHI & AI Identity Journal

The latest on NHI and Agentic AI security – articles, research, breaches, news and events every week.

Bonus 33% off our NHI Course when you subscribe.

NHIMG Editorial Note
Researched and written by the NHI Mgmt Group editorial team using AI tools, under the editorial direction of Lalit Choda. Facts are drawn from the sources listed on this page and checked by our automated quality process. Last updated 14 November 2026. Spotted an error? Use our contact page.
NHI Mgmt Group, the independent authority on Non-Human Identity, IAM and Agentic AI security. nhimg.org

PDF Downloads for Newsletter Subscribers

Get the guide

Enter your details and we’ll email you a download link.

The full guide is free to read online. The PDF is a thank you for subscribing.

Fill in all fields marked * and tick the PDF box to continue.