From OpenAPI to MCP: expose a REST API to your agent without full access

A few REST actions and interpretable responses: from OpenAPI to a bounded MCP catalog without giving the agent full access.

API specification turned into a short catalogue of tools

Your agent needs a few actions from your REST API and responses it can interpret. Use OpenAPI as an inventory, design a bounded catalog, and publish those tools over MCP when you want to reuse them from different clients.

"Has my order shipped, and when will it arrive?" Your store's frontend calls GET /orders/ORD-42. Its code knows that status_code: 20 means the order has left the warehouse and that eta is the estimated delivery date. If the agent receives the same JSON, with warehouse and carrier data and internal fields, it has to find the relevant information and interpret codes whose translation usually lives in the client that consumes the API.

This article follows that order from the API documented in OpenAPI to a tool the agent can use. To decide when MCP makes more sense than a bounded command, you can keep reading in MCP vs CLI. If you are designing the name, schema, or errors of a tool, there is more detail in tool contracts.

What changes when you give an API to the agent

You can connect the agent directly to REST. If you control the runtime, you can register a few functions and have them call the API with the contract, permissions, and output format you need. MCP gives you a common protocol when those same functions must be available to other clients.

Approach

What the model has to do

What the code does

API exposed as-is

Chooses among the operations the runtime offers, fills in their parameters, and interprets the raw results.

Runs the calls and returns the API data.

Domain tools in your runtime

Chooses an action such as get_order_status, passes the order number, and receives a status it can explain to the user.

Validates arguments and permissions, builds the request, and prepares the response.

The same tools published over MCP

Uses the same business contract from a compatible client.

Exposes the catalog with tools/list and receives invocations through tools/call. Each handler runs its tool's logic.

Importing a large specification is convenient for exploration. The cost appears if the runtime sends the model descriptions of routes it does not need and then passes it every full response. The agent spends context choosing among irrelevant operations and reading results that could be reduced in code. The scope of the credential also matters. A tool with permission over all accounts can reach another customer's resources even if the chat is already tied to a tenant. MCP tools specification · Writing effective tools for AI agents, by Anthropic

Before and after a REST call

Back to the order. This is an illustrative fragment of what the frontend receives:

{
  "id": "ORD-42",
  "status_code": 20,
  "eta": "2026-12-02",
  "warehouse_id": 8,
  "carrier_id": 3,
  "flags": 4
}
{
  "id": "ORD-42",
  "status_code": 20,
  "eta": "2026-12-02",
  "warehouse_id": 8,
  "carrier_id": 3,
  "flags": 4
}
{
  "id": "ORD-42",
  "status_code": 20,
  "eta": "2026-12-02",
  "warehouse_id": 8,
  "carrier_id": 3,
  "flags": 4
}

Preprocessing. Offer get_order_status with a single argument, order_id. The server validates its format, obtains the identity from the authorized context, and builds the request to the known route. If your API supports field selection, filters, or pagination, apply them at the source. A smaller catalog reduces the context the model needs to choose. Limiting the query reduces the data the adapter has to receive and process.

Postprocessing. The adapter uses the product's status table to translate 20 into shipped, renames eta to estimated_delivery_date, and keeps the order identifier. If the carrier has not yet calculated a date, the field is returned as null. The date is still an estimate. Less data reaches the model on the next turn, and the meaning of each field is explicit.

{
  "order_id": "ORD-42",
  "status": "shipped",
  "estimated_delivery_date": "2026-12-02"
}
{
  "order_id": "ORD-42",
  "status": "shipped",
  "estimated_delivery_date": "2026-12-02"
}
{
  "order_id": "ORD-42",
  "status": "shipped",
  "estimated_delivery_date": "2026-12-02"
}

If the API returns HTML for an error or a diagnostic body, convert it into a status the agent can handle, such as ORDER_NOT_FOUND or ORDER_API_UNAVAILABLE. For debugging, log the technical details you need and filter out secrets and sensitive data. Writing effective tools for AI agents

From OpenAPI inventory to tool catalog

Use OpenAPI to locate operations, parameters, and authentication requirements. The import can generate a draft. Review what function each operation serves before enabling it in the catalog.

Decision

Criterion

Example

Publish as a tool

The agent needs a specific business action and its effect is defined.

Checking an order's status with get_order_status.

Wrap and narrow

The endpoint accepts more operations or fields than the agent needs.

Turning a twenty-field PATCH into a tool that only allows changing the delivery address.

Exclude

The operation is administrative, diagnostic, or outside the use case.

Deleting users, bulk exports, or the general order listing with internal filters.

Keep the essential fields required. Define the optional ones that have a clear use, limit lists and ranges, and close the schema to additional properties when the arguments are bounded. The tenant, the credential, and the endpoint are resolved on the server. A tool can map to a single route or compose several calls if the task requires it. OpenAPI specification · Building effective agents, by Anthropic

Generic example: from OpenAPI to an MCP tool

From the OpenAPI we take GET /orders/{orderId} and its path parameter. We define get_order_status with order_id as the only argument and an output containing the status and the estimated date. In the example, the orders API supports fields to select the response. If your API always returns the full body, apply the transformation in the handler.

This snippet uses the official TypeScript SDK on its 1.x branch. resolveCaller is code from your application. It uses the identity authenticated by the MCP server, checks membership in the active tenant, and returns the caller's permissions. issueOrdersToken obtains a credential intended for the orders API, limited to the tenant and the indicated permission. The API checks that credential and that the order belongs to the authorized organization. SDK guide for MCP servers

import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'
import { z } from 'zod/v4'

const server = new McpServer({ name: 'support-tools', version: '1.0.0' })
const statusByCode = new Map([
  [10, 'pending'],
  [20, 'shipped'],
  [30, 'delivered'],
])

function toolError(code) {
  return { isError: true, content: [{ type: 'text', text: code }] }
}

async function getOrderStatus(orderId, apiToken) {
  const url = new URL('https://api.example.com/orders/' + encodeURIComponent(orderId))
  url.searchParams.set('fields', 'id,status_code,eta')

  const response = await fetch(url, {
    method: 'GET',
    headers: { Authorization: 'Bearer ' + apiToken, Accept: 'application/json' },
    signal: AbortSignal.timeout(5000),
  })

  if (response.status === 404) return toolError('ORDER_NOT_FOUND')
  if (!response.ok) return toolError('ORDER_API_UNAVAILABLE')

  const order = await response.json()
  const result = {
    order_id: orderId,
    status: statusByCode.get(order.status_code) ?? 'unknown',
    estimated_delivery_date: typeof order.eta === 'string' ? order.eta : null,
  }

  return {
    structuredContent: result,
    content: [{ type: 'text', text: JSON.stringify(result) }],
  }
}

server.registerTool(
  'get_order_status',
  {
    description: 'Looks up the status and estimated delivery date of an order.',
    inputSchema: z.strictObject({ order_id: z.string().regex(/^ORD-[0-9]{1,12}$/) }),
    outputSchema: {
      order_id: z.string(),
      status: z.enum(['pending', 'shipped', 'delivered', 'unknown']),
      estimated_delivery_date: z.string().nullable(),
    },
  },
  async ({ order_id }, request) => {
    try {
      const caller = await resolveCaller(request.authInfo)
      if (!caller?.permissions.includes('orders:read')) return toolError('FORBIDDEN')

      const apiToken = await issueOrdersToken({
        tenantId: caller.tenantId,
        userId: caller.userId,
        scope: 'orders:read',
      })

      return await getOrderStatus(order_id, apiToken)
    } catch {
      return toolError('ORDER_API_UNAVAILABLE')
    }
  },
)
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'
import { z } from 'zod/v4'

const server = new McpServer({ name: 'support-tools', version: '1.0.0' })
const statusByCode = new Map([
  [10, 'pending'],
  [20, 'shipped'],
  [30, 'delivered'],
])

function toolError(code) {
  return { isError: true, content: [{ type: 'text', text: code }] }
}

async function getOrderStatus(orderId, apiToken) {
  const url = new URL('https://api.example.com/orders/' + encodeURIComponent(orderId))
  url.searchParams.set('fields', 'id,status_code,eta')

  const response = await fetch(url, {
    method: 'GET',
    headers: { Authorization: 'Bearer ' + apiToken, Accept: 'application/json' },
    signal: AbortSignal.timeout(5000),
  })

  if (response.status === 404) return toolError('ORDER_NOT_FOUND')
  if (!response.ok) return toolError('ORDER_API_UNAVAILABLE')

  const order = await response.json()
  const result = {
    order_id: orderId,
    status: statusByCode.get(order.status_code) ?? 'unknown',
    estimated_delivery_date: typeof order.eta === 'string' ? order.eta : null,
  }

  return {
    structuredContent: result,
    content: [{ type: 'text', text: JSON.stringify(result) }],
  }
}

server.registerTool(
  'get_order_status',
  {
    description: 'Looks up the status and estimated delivery date of an order.',
    inputSchema: z.strictObject({ order_id: z.string().regex(/^ORD-[0-9]{1,12}$/) }),
    outputSchema: {
      order_id: z.string(),
      status: z.enum(['pending', 'shipped', 'delivered', 'unknown']),
      estimated_delivery_date: z.string().nullable(),
    },
  },
  async ({ order_id }, request) => {
    try {
      const caller = await resolveCaller(request.authInfo)
      if (!caller?.permissions.includes('orders:read')) return toolError('FORBIDDEN')

      const apiToken = await issueOrdersToken({
        tenantId: caller.tenantId,
        userId: caller.userId,
        scope: 'orders:read',
      })

      return await getOrderStatus(order_id, apiToken)
    } catch {
      return toolError('ORDER_API_UNAVAILABLE')
    }
  },
)
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'
import { z } from 'zod/v4'

const server = new McpServer({ name: 'support-tools', version: '1.0.0' })
const statusByCode = new Map([
  [10, 'pending'],
  [20, 'shipped'],
  [30, 'delivered'],
])

function toolError(code) {
  return { isError: true, content: [{ type: 'text', text: code }] }
}

async function getOrderStatus(orderId, apiToken) {
  const url = new URL('https://api.example.com/orders/' + encodeURIComponent(orderId))
  url.searchParams.set('fields', 'id,status_code,eta')

  const response = await fetch(url, {
    method: 'GET',
    headers: { Authorization: 'Bearer ' + apiToken, Accept: 'application/json' },
    signal: AbortSignal.timeout(5000),
  })

  if (response.status === 404) return toolError('ORDER_NOT_FOUND')
  if (!response.ok) return toolError('ORDER_API_UNAVAILABLE')

  const order = await response.json()
  const result = {
    order_id: orderId,
    status: statusByCode.get(order.status_code) ?? 'unknown',
    estimated_delivery_date: typeof order.eta === 'string' ? order.eta : null,
  }

  return {
    structuredContent: result,
    content: [{ type: 'text', text: JSON.stringify(result) }],
  }
}

server.registerTool(
  'get_order_status',
  {
    description: 'Looks up the status and estimated delivery date of an order.',
    inputSchema: z.strictObject({ order_id: z.string().regex(/^ORD-[0-9]{1,12}$/) }),
    outputSchema: {
      order_id: z.string(),
      status: z.enum(['pending', 'shipped', 'delivered', 'unknown']),
      estimated_delivery_date: z.string().nullable(),
    },
  },
  async ({ order_id }, request) => {
    try {
      const caller = await resolveCaller(request.authInfo)
      if (!caller?.permissions.includes('orders:read')) return toolError('FORBIDDEN')

      const apiToken = await issueOrdersToken({
        tenantId: caller.tenantId,
        userId: caller.userId,
        scope: 'orders:read',
      })

      return await getOrderStatus(order_id, apiToken)
    } catch {
      return toolError('ORDER_API_UNAVAILABLE')
    }
  },
)

Connect the instance to an MCP transport with your application's authentication. If you use the adapter as an internal function, apply the same schema, resolve the identity from your session, and use the authorized credential to call getOrderStatus. In both cases, the model supplies the order number. MCP clients that support structured results can use structuredContent in the model's context. The text block serves as a compatible representation. Structured results and errors in MCP

What changes when the tool writes

The same API has POST /orders/{orderId}/refunds. You can expose create_refund if the assistant needs to run that operation. Define order_id and the amount as an integer in the minor units of the order's currency. The backend checks that the user has permission, that the order belongs to the tenant, that the amount is within the refundable balance, and that the cap and approval set by policy are met.

If a network failure occurs, the backend reuses the same idempotency key for retries of that approved operation. The API recognizes the key and avoids repeating the effect. Each approved refund has its own identifier. If the copilot only proposes refunds, you can offer a tool with permissions to prepare the request and submit it for review. Idempotent requests in the Stripe API

For a remote connection, distinguish the client's authorization to the MCP from the one the MCP uses to your REST API. Each credential has its own audience. The adapter's technical identity can be shared if every call carries a verifiable tenant context and the API enforces it when authorizing the resource. The same check applies to reads and writes. Authorization in MCP · MCP security best practices

Checklist before opening the catalog to clients

Step

What to check

Inventory

Every operation is classified. OpenAPI changes go through review before the published catalog is expanded.

Contract

Names describe actions, parameters are bounded, and errors have a format the agent can handle.

Authorization

The credential is obtained on the server. A read or write outside the tenant is denied even if the identifier exists.

Effects

A retry of a mutation uses the same idempotency key. Approval, when required, is recorded.

Response

Test unknown statuses, missing fields, large pages, and backend errors. Keep the IDs the agent will need later.

Observability

Log the call identifier, the tool, the tenant, the latency, and the result, filtering sensitive data.

To measure the effect on inference, run the same questions with the same model using the original API responses and the tool's responses. Compare input tokens per task, the number of calls, and answer accuracy. This shows how much context you save and whether the agent interprets the data better. Evaluating tools for agents

How Devic handles it in practice

In My MCPs you can import an OpenAPI URL or upload a JSON file to generate a proposed set of tools, or start with an empty catalog. Review the proposal and enable the operations the assistant needs. For the orders case, configure get_order_status with method GET and endpoint /orders/${order_id}. Map order_id as a path parameter, configure the credential for the API, and apply postprocessing to return the status and the estimated date. Test the call with the same identity and policy you will use in production. Import OpenAPI · Configure and test tools

If you manage it through the API, the POST /v1/tool-servers reference documents url, toolDefinitions, authenticationConfig, and mcpType. In Devic's configuration, the schema is described in function.parameters. The adapter uses method, endpoint, and the path, query, or body keys to build the request. You can prepare the response with responsePostProcessingEnabled and responsePostProcessingTemplate. Create a tool server · Tool Servers API

For the same order, this expression transforms the output in the tool's configuration.

response.status === 200
  ? {
      order_id: response.body.id,
      status: ({ 10: 'pending', 20: 'shipped', 30: 'delivered' })[
        response.body.status_code
      ] ?? 'unknown',
      estimated_delivery_date: response.body.eta ?? null,
    }
  : { error: response.status === 404 ? 'ORDER_NOT_FOUND' : 'ORDER_API_UNAVAILABLE' }
response.status === 200
  ? {
      order_id: response.body.id,
      status: ({ 10: 'pending', 20: 'shipped', 30: 'delivered' })[
        response.body.status_code
      ] ?? 'unknown',
      estimated_delivery_date: response.body.eta ?? null,
    }
  : { error: response.status === 404 ? 'ORDER_NOT_FOUND' : 'ORDER_API_UNAVAILABLE' }
response.status === 200
  ? {
      order_id: response.body.id,
      status: ({ 10: 'pending', 20: 'shipped', 30: 'delivered' })[
        response.body.status_code
      ] ?? 'unknown',
      estimated_delivery_date: response.body.eta ?? null,
    }
  : { error: response.status === 404 ? 'ORDER_NOT_FOUND' : 'ORDER_API_UNAVAILABLE' }

You can assign the catalog to the agent or to the assistant. If external clients are going to consume it, publish the MCP with the visibility you need. Devic can also connect to remote MCP servers and enable their tools in agents and assistants. The catalog integrations that each user connects with their own account have their own flow. Publish an MCP · Connected MCPs · Integrations for end users

Devic takes care of hosting and connecting the catalog, running the configured mapping, and logging the calls. Your application defines which operations are offered, what data each tool returns, and who has permission to use it. To see how it fits with the rest of the runtime, you can read the model is not the agent. To try the flow, there is the Devic product and the public documentation.

Alberto Iglesias

CEO

Turn your SaaS AI-Native

Get a free trial just by signing up


Ready to turn your platform AI-Native?

Centralize agents, tools, and flows in one platform and start scaling with less friction.

Build and run agents without friction

Connect your current infrastructure

  • Devic AI

  • Devic AI

  • Devic AI

Ready to turn your platform AI-Native?

Centralize agents, tools, and flows in one platform and start scaling with less friction.

Build and run agents without friction

Connect your current infrastructure

  • Devic AI

  • Devic AI

  • Devic AI