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.
| Transformation | What the converter does | Decision hidden in the default | Risk if left unreviewed |
|---|---|---|---|
| Operation selection | Reads paths and methods and decides which become tools, resources or nothing | Which operations the model can call | Operation over-exposure (admin, delete, bulk export) |
| Naming | Derives a tool name, usually from operationId, summary or method plus path | How the model distinguishes similar operations | Tool confusion, wrong operation chosen |
| Description and schema mapping | Copies summary, description, parameters and request body schema into description and inputSchema | What the model is told and what arguments are accepted | Poor or injected descriptions, permissive inputs |
| Request execution | Builds the HTTP request with a configured client, base URL and headers | Which credential and which network path every call uses | Credential 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-allRouteMap(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
- 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: allowon 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. - Allowlist, never denylist. Match approved operations by
operationIdor by tag and exclude everything else. - 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.
- 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. - 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: Bearerheader on the client passed tofrom_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.
| Pattern | Who the backend sees | Blast radius | When it is acceptable |
|---|---|---|---|
| Shared static API key on the client | One service identity for all users | Union of every generated tool's needs | Read-only, non-sensitive internal data, single-tenant prototypes |
| Caller's token forwarded unchanged | The user, with a token never meant for this API | Anything the token's audience allows, plus loss of audit | Never: forbidden by the MCP authorisation specification |
| Dedicated workload identity per server, scoped to allowlisted operations | The agent service, consistently | Only the approved operations | Autonomous back-office agents with no user context |
| Token exchange to a downstream token bound to the API audience | The user, with the agent recorded as actor | The user's rights, narrowed to the requested scope | User-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
operationIdup 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 asupdate_item_2andupdate_item_3are 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
- Override names explicitly. FastMCP accepts an
mcp_namesmap fromoperationIdto tool name; name by effect and object, for exampleinvoice_get_by_idorticket_close_permanently. - Replace descriptions rather than appending to them. FastMCP's
mcp_component_fnlets 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. - 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.
- 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. - Add an output schema and return only the fields the task needs. The MCP specification requires servers that declare an
outputSchemato 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). - 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/listper caller so that an agent only sees tools its role may use. - Invocation: enforce authorisation on every
tools/callat 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
serversentry cannot redirect traffic. Operations that accept URLs as parameters need an allowlist and an egress proxy. - Errors: FastMCP's
mask_error_details=Truehides 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 class | Expose by generation? | Annotations to set | Extra control |
|---|---|---|---|
| Read, single object | Yes, if on the allowlist | readOnlyHint true | Object-level authorisation at the API (API1:2023) |
| Read, list or search | Yes, with bounded page size | readOnlyHint true | Output field allowlist, result cap |
| Bulk export | No | Not applicable | Separate reviewed tool with volume limits |
| Create or update | Only with an allowlist and strict schema | readOnlyHint false, destructiveHint false, idempotentHint as true for real PUT semantics | Idempotency keys, per-user rate limits |
| Delete, purge, payment, send | No: hand-written wrapper | destructiveHint true | Confirmation, dry run, human approval (ATLAS AML.M0029) |
| Administrative (users, roles, keys, config) | No | Not applicable | Keep 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-keyand records anagent-idheader 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.Bodyin 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
- 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. - 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.
- Export and diff the catalogue. Call
tools/liston 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. - Review model-facing text. A named reviewer approves each description and schema as prompt text, using the rewrite rules above.
- 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.
- 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.
- 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
destructiveHintto trigger confirmation when some hosts ignore it.
Framework mapping
| Control area | NIST SP 800-53 Rev 5 | NIST CSF 2.0 | OWASP and MITRE ATLAS |
|---|---|---|---|
| Operation allowlist and tool count budget | AC-6 Least Privilege, CM-8 System Component Inventory | PR.AA-05 | LLM06:2025 Excessive Agency, API5:2023 Broken Function Level Authorization |
| Per-call authorisation and object checks | AC-3 Access Enforcement | PR.AA-05 | API1:2023, AML.T0053 AI Agent Tool Invocation |
| No token passthrough, dedicated server identity | IA-5 Authenticator Management, IA-9 Service Identification and Authentication | PR.AA-05 | API2:2023 Broken Authentication, AML.T0098 AI Agent Tool Credential Harvesting |
| Description review, strict schemas | SI-10 Information Input Validation | PR.PS-01 | AML.T0051 LLM Prompt Injection |
| Catalogue diff and change control | CM-3 Configuration Change Control | PR.PS-01 | LLM06:2025 |
| Tool call logging | AU-2 Event Logging, AU-12 Audit Record Generation | DE.CM-09 | AML.T0086 Exfiltration via AI Agent Tool Invocation |
| Human approval for destructive tools | AC-6 | PR.AA-05 | AML.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/listcatalogue in CI and fail builds on unreviewed changes. - Track exposure ratio, write share and drift events per server.
Standards and references
- Model Context Protocol: Security Best Practices
- Model Context Protocol: Tools specification (2025-11-25)
- Model Context Protocol: Schema reference, Tool and ToolAnnotations
- OpenAPI Initiative: OpenAPI Specification v3.1.1
- OWASP: LLM06:2025 Excessive Agency
- OWASP: API5:2023 Broken Function Level Authorization
- FastMCP: OpenAPI integration documentation
- Microsoft Learn: Expose a REST API in API Management as an MCP server
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