Spring AI MCP From OpenAPI: Turning Your Existing REST API Into AI Tools
The most common question after my Spring AI MCP Server article wasn’t about transports or security. It was this:
“We have hundreds of REST endpoints, all documented with OpenAPI. Do we really have to hand-write an
@McpToolfor every single one?”
Fair question. Annotating three OrderService methods is a nice tutorial. Annotating a whole API by hand is busywork. You’d be duplicating information that already lives in your OpenAPI spec: the operation names, the parameter types, the descriptions, the request body schemas.
So this article covers the obvious next step: generating MCP tools from the OpenAPI spec you already have. There are two routes in the Spring world, and they solve different problems:
- Your own Spring Boot app: use the springdoc-openapi MCP starter, which turns your documented controllers into MCP tools in the same process.
- Someone else’s API (another team’s service, a SaaS API, a non-Spring backend): write a small Spring AI
ToolCallbackProviderthat reads the spec and proxies calls over HTTP.
I’ll walk through both. Then comes the part that matters more than the code: why “expose every endpoint” is the wrong default.
Versions: every Java snippet below compiles against Spring Boot 4.1.2, Spring AI 2.0.2 and springdoc-openapi 3.2.0. I also ran the Route 2 code against a test spec and a local HTTP server.
Route 1: springdoc-openapi Does It For You
If you use springdoc-openapi to generate your OpenAPI docs (most Spring Boot teams I know do), the project now ships an MCP integration built on Spring AI. Every operation in the generated spec becomes an MCP tool:
- The tool name comes from the
operationId, converted to snake_case. - The description comes from
summary/description. - The input schema is built from path, query and header parameters plus the request body, with
$ref,allOf/oneOf/anyOfand validation constraints resolved.
Step 1: Dependency
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-starter-webmvc-mcp</artifactId>
<version>3.2.0</version>
</dependency>
There’s a springdoc-openapi-starter-webflux-mcp twin for reactive apps. springdoc 3.x is the Spring Boot 4 line, so if you’re still on Boot 3 this route isn’t open to you yet.
Use 3.1.1 or later, no exceptions. The 3.1.1 release fixed five MCP security advisories: path parameters weren’t encoded in tool calls (request retargeting), the MCP and dashboard endpoints were exposed by default, audit logs stored credentials unredacted, the pending-confirmation store could grow without bound, and request headers could leak between concurrent WebFlux requests. If you tried an earlier version, that’s reason enough to upgrade before going further.
Step 2: Turn It On
Since 3.1.1, MCP is opt-in. Adding the dependency does nothing until you set:
springdoc.ai.mcp.enabled=true
# Optional: a dashboard at /mcp-ui to list and test tools
springdoc.ai.mcp.dashboard-enabled=true
# Optional: use Spring AI's stateless server (springdoc 3.2.0+)
spring.ai.mcp.server.protocol=STATELESS
Clients connect at /mcp. The dashboard is worth turning on in dev. It lists every generated tool, lets you execute one with JSON input, exports the cURL equivalent, and warns you when a response is bigger than 2 KB. That last one matters more than it looks; I’ll come back to it.
Step 3: Write Descriptions for Agents, Not Humans
Your OpenAPI summaries were written for a developer skimming Swagger UI. “Get order” is fine for a human who can see the URL and the response schema. An agent choosing between 40 tools needs to know when to call it.
springdoc gives you @McpToolDescription to override the OpenAPI text for MCP only:
@RestController
@RequestMapping("/api/orders")
@Tag(name = "orders")
public class OrderController {
@Operation(summary = "Get order")
@McpToolDescription(
value = "Look up one order by its ID (format ORD-12345). "
+ "Use this when the user gives an order number. "
+ "To find orders by customer, use search_orders instead.",
name = "get_order")
@GetMapping("/{orderId}")
public OrderDto getOrder(@PathVariable String orderId) {
return orderService.find(orderId);
}
}
Swagger UI keeps its short summary, and the agent gets a description that tells it what to use the tool for and what to use instead.
Step 4: Exclude Aggressively
By default every documented operation becomes a tool. Don’t ship that. An McpToolCustomizer bean lets you rename, re-describe, edit the schema, or drop endpoints:
@Configuration
public class McpToolsConfig {
private static final Set<String> EXPOSED_TAGS = Set.of("orders", "inventory");
@Bean
public McpToolCustomizer onlyAgentFacingTools() {
return (context, path, method, operation) -> {
List<String> tags = operation.getTags();
boolean agentFacing = tags != null && tags.stream().anyMatch(EXPOSED_TAGS::contains);
if (!agentFacing || path.startsWith("/api/admin")) {
context.setExclude(true);
}
return context;
};
}
}
Use setExclude(true) rather than returning null; the springdoc docs recommend it. I prefer an allowlist (tags you opt in) over a denylist. A new endpoint someone adds next month should not silently become an AI tool.
Step 5: Understand the Mutating-Call Guardrail
springdoc classifies tools by HTTP method. GET, HEAD and OPTIONS are “safe”, and everything else is “mutating”. By default, when an agent calls a mutating tool, the HTTP request is not executed. The agent instead gets a JSON response flagged requires_human_approval, with the method, path and arguments, so a person can confirm it.
# The default; keep it unless you have a real reason
springdoc.ai.mcp.guardrails.require-approval-for-mutating-tools=true
You can override the classification per endpoint with context.setSafeEndpoint(...) in a customizer. That’s useful for a POST that is really a search.
But read the fine print: the springdoc docs are explicit that this is a confirmation step, not an access control. A caller who can reach the endpoint can approve its own request. It stops an agent from cancelling orders by accident. It does not stop anyone who wants to cancel orders on purpose.
Step 6: Lock Down /mcp Yourself
The MCP endpoints have no authentication or authorization of their own. Your controllers’ security still applies when the tool calls them, but the MCP transport, dashboard and admin API need their own rules:
@Bean
@Order(1)
SecurityFilterChain mcpSecurity(HttpSecurity http) throws Exception {
http
.securityMatcher("/mcp/**", "/mcp-ui/**", "/api/mcp-admin/**")
.authorizeHttpRequests(auth -> auth.anyRequest().hasRole("MCP_CLIENT"))
.oauth2ResourceServer(oauth2 -> oauth2.jwt(Customizer.withDefaults()));
return http.build();
}
Put the dashboard behind a stricter role than the MCP endpoint, or simply leave dashboard-enabled off in production. A page that executes arbitrary tools with forwarded auth headers is not something to leave public.
Route 2: An OpenAPI-Backed ToolCallbackProvider
Route 1 only works for the app you’re running. Often the API you want agents to use belongs to someone else: the billing team’s service, a vendor API, a Go or Python backend that publishes an openapi.json. For that, build an MCP server that reads the spec and proxies calls.
Spring AI makes this surprisingly small, because the MCP server starter registers any ToolCallback or ToolCallbackProvider bean as MCP tools. You need two classes: one ToolCallback per operation, and a provider that builds them from the spec.
Dependencies on top of spring-ai-starter-mcp-server-webmvc:
<dependency>
<groupId>io.swagger.parser.v3</groupId>
<artifactId>swagger-parser</artifactId>
<version>2.1.22</version>
</dependency>
The Provider: Parse, Filter, Build
public class OpenApiToolCallbackProvider implements ToolCallbackProvider {
private final ToolCallback[] callbacks;
public OpenApiToolCallbackProvider(String specLocation, RestClient restClient,
Set<String> allowedOperationIds) {
ParseOptions options = new ParseOptions();
options.setResolve(true);
options.setResolveFully(true); // inline every $ref so each tool schema is self-contained
OpenAPI api = new OpenAPIV3Parser().read(specLocation, null, options);
if (api == null) {
throw new IllegalStateException("Could not parse OpenAPI spec at " + specLocation);
}
this.callbacks = api.getPaths().entrySet().stream()
.flatMap(path -> path.getValue().readOperationsMap().entrySet().stream()
.filter(op -> allowedOperationIds.contains(op.getValue().getOperationId()))
.map(op -> new OpenApiOperationToolCallback(
path.getKey(), op.getKey(), op.getValue(), restClient)))
.toArray(ToolCallback[]::new);
}
@Override
public ToolCallback[] getToolCallbacks() {
return callbacks;
}
}
Note the explicit allowedOperationIds, checked before a callback is built, so a sloppy operation elsewhere in the spec (no operationId, odd content types) can’t break startup. Same rule as Route 1: allowlist, never “everything in the spec”.
The Callback: Schema In, HTTP Out
public class OpenApiOperationToolCallback implements ToolCallback {
private static final ObjectMapper JSON = io.swagger.v3.core.util.Json.mapper();
private final String path;
private final PathItem.HttpMethod method;
private final Operation operation;
private final RestClient restClient;
private final ToolDefinition definition;
public OpenApiOperationToolCallback(String path, PathItem.HttpMethod method,
Operation operation, RestClient restClient) {
this.path = path;
this.method = method;
this.operation = operation;
this.restClient = restClient;
this.definition = ToolDefinition.builder()
.name(operation.getOperationId())
.description(Stream.of(operation.getDescription(), operation.getSummary())
.filter(Objects::nonNull)
.findFirst()
.orElse(operation.getOperationId())) // many specs have neither
.inputSchema(buildInputSchema())
.build();
}
@Override
public ToolDefinition getToolDefinition() {
return definition;
}
@Override
public String call(String toolInput) {
JsonNode args = readArgs(toolInput);
Map<String, Object> pathVariables = new HashMap<>();
RestClient.RequestBodySpec request = restClient
.method(HttpMethod.valueOf(method.name()))
.uri(uri -> {
uri.path(path);
for (Parameter p : parameters()) {
JsonNode value = args.get(p.getName());
if (value == null) continue;
switch (p.getIn()) {
case "path" -> pathVariables.put(p.getName(), value.asText());
case "query" -> uri.queryParam(p.getName(), value.asText());
default -> { } // headers: set from server-side config, never from the agent
}
}
return uri.build(pathVariables); // expands AND encodes path variables
});
if (args.has("body")) {
request.contentType(MediaType.APPLICATION_JSON).body(args.get("body").toString());
}
return request.retrieve().body(String.class);
}
private String buildInputSchema() {
ObjectNode schema = JSON.createObjectNode().put("type", "object");
ObjectNode properties = schema.putObject("properties");
ArrayNode required = schema.putArray("required");
for (Parameter p : parameters()) {
if (!"path".equals(p.getIn()) && !"query".equals(p.getIn())) continue;
ObjectNode prop = toJsonSchema(p.getSchema());
if (p.getDescription() != null) prop.put("description", p.getDescription());
properties.set(p.getName(), prop);
if (Boolean.TRUE.equals(p.getRequired())) required.add(p.getName());
}
RequestBody body = operation.getRequestBody();
if (body != null && body.getContent() != null
&& body.getContent().get("application/json") != null) {
properties.set("body",
toJsonSchema(body.getContent().get("application/json").getSchema()));
if (Boolean.TRUE.equals(body.getRequired())) required.add("body");
}
return schema.toString();
}
private static ObjectNode toJsonSchema(Schema<?> schema) {
ObjectNode node = JSON.valueToTree(schema);
// swagger-core serializes "default": null everywhere; strip it so the model sees a clean schema
node.findParents("default").forEach(parent -> {
if (parent.get("default").isNull()) ((ObjectNode) parent).remove("default");
});
return node;
}
private List<Parameter> parameters() {
return Objects.requireNonNullElse(operation.getParameters(), List.of());
}
private static JsonNode readArgs(String toolInput) {
try {
return JSON.readTree(toolInput == null || toolInput.isBlank() ? "{}" : toolInput);
} catch (JsonProcessingException e) {
throw new IllegalArgumentException("Tool input is not valid JSON", e);
}
}
}
A few choices here that are easy to get wrong:
- Path variables go through
UriBuilder.build(Map), which encodes them. Concatenating"/orders/" + orderIdlets an agent send../admin/usersand hit a different endpoint. That’s exactly the bug springdoc fixed in 3.1.1, so don’t reintroduce it in your own code. - Header parameters are never taken from the agent. Auth tokens and tenant IDs come from server-side config on the
RestClient, not from model output. - The request body is nested under a
bodyproperty so it can’t collide with a query parameter of the same name.
Wiring It Up
@Bean
ToolCallbackProvider billingApiTools(RestClient.Builder builder,
@Value("${billing.api.token}") String token) {
RestClient client = builder
.baseUrl("https://billing.internal.example.com")
.defaultHeader(HttpHeaders.AUTHORIZATION, "Bearer " + token)
.build();
return new OpenApiToolCallbackProvider(
"https://billing.internal.example.com/v3/api-docs",
client,
Set.of("getInvoice", "listInvoicesByCustomer", "getPaymentStatus"));
}
Three read-only operations from a billing API, exposed over MCP, without writing a single @McpTool. When the billing team adds a field to Invoice, your tool schema picks it up on the next restart.
This is a sketch, not a library. It skips oneOf request bodies, non-JSON content types, pagination, and response trimming. But it shows how little separates an OpenAPI spec from a working set of MCP tools.
Why “Expose Everything” Is the Wrong Default
Both routes make it trivially easy to turn 200 endpoints into 200 tools. Please don’t.
1. Tool count hurts agents. Every tool definition is sent to the model on each request. Hundreds of tool schemas eat context, cost tokens on every call, and make the model worse at picking the right tool. Several MCP clients also cap how many tools they’ll load. My rule from the last article still applies: start with a handful of tools for one job, then grow.
2. REST granularity isn’t agent granularity. A UI might call GET /customers/{id}, GET /customers/{id}/orders and GET /orders/{id}/shipments to render one screen. An agent asked “where’s Marie’s last order?” would need to chain all three correctly. Sometimes the right answer is one purpose-built @McpTool that wraps three calls, alongside a few generated ones.
3. Responses are sized for UIs, not context windows. A list endpoint that returns 50 fully-hydrated objects is fine for a browser. As a tool result, it burns thousands of tokens the model mostly ignores. That’s why springdoc’s dashboard flags responses over 2 KB. Prefer endpoints with pagination and sparse field sets, or add a projection.
4. Mutating endpoints need a human or a hard “no”. Generated tools inherit every POST, PUT and DELETE in the spec. Keep springdoc’s approval guardrail on, and in Route 2 only allowlist safe operations unless you’ve thought hard about the blast radius.
5. Descriptions are prompts now. Once an OpenAPI description becomes a tool description, it’s part of the agent’s prompt. Treat changes to it like code changes: review them, and don’t let a vendor spec you don’t control inject instructions into your agent unchecked.
Which Route Should You Pick?
| Scenario | Recommendation |
|---|---|
| Your own Spring Boot 4 app, documented with springdoc | ✅ springdoc MCP starter (Route 1) |
| Your own app, still on Spring Boot 3 | ⚠️ Hand-written @McpTools, or Route 2 against your own /v3/api-docs |
| Another team’s or a vendor’s API with an OpenAPI spec | ✅ Custom ToolCallbackProvider (Route 2) |
| A handful of high-value, multi-step workflows | ✅ Hand-written @McpTool wrapping several calls |
| ”Let agents use our whole API” | ❌ Neither. Pick the five tools that do the job first. |
The Bottom Line
You don’t need to hand-write an MCP tool for every endpoint. The OpenAPI spec you already maintain carries almost everything an MCP tool needs, and in 2026 the Spring ecosystem can generate tools from it in an afternoon.
What the spec can’t tell you is which endpoints an agent should be allowed to call, how to describe them so a model picks the right one, and which ones need a human in the loop. That part is still your job:
- Allowlist, don’t denylist. New endpoints shouldn’t become AI tools by accident.
- Rewrite descriptions for agents. Say when to use the tool, not just what it returns.
- Secure
/mcplike any other API. Approval prompts are a seatbelt, not a lock.
See the springdoc-openapi MCP documentation for the full list of properties and the dashboard API.
Related Articles
If you’re building AI agents with Spring Boot, read these next:
- Spring AI MCP Server: Exposing Your Spring Boot App to AI Agents — The hand-written approach:
@McpTool, transports, and security rules. - Spring AI Agent Loops in Production: Tool Calling, Memory, and Guardrails — The other side of MCP: the agents that call these tools.
- Spring AI + RAG in Production: Structured Output, Ollama, and pgvector — Giving agents knowledge, not just tools.
Enjoying the content? Here are tools I personally use and recommend:
- 🌐 Hosting: Bluehost — simple hosting for a WordPress or PHP site
- 🛒 Tech Gear: My Amazon Store — keyboards, monitors, dev tools I use
Purchases through my links help keep this blog ad-free 💙
Enjoyed this post?
Every clash gets a video: two tools, one real task, a measured winner.
▶ Subscribe on YouTube 🎬 All videos