Saltar al contenido principal

How to Build and Manage MCP-Based Agents from Your API Contracts

· 19 min de lectura
Adrian Escutia
La Rebelion Founder

What you will learn

  • How to build an MCP-based agent without writing tool code.
  • How to define capabilities in OpenAPI 3.x contracts with intent-based planning.
  • How to give the agent a transparent harness in VS Code.
  • How to test, measure, deploy, and manage an MCP-based agent over time.

An agent is a Large Language Model (LLM) that works in a loop: it reads instructions and a request, decides on the next action, calls a tool, reads the result, and repeats until it can answer. Most agent frameworks put the intelligence in that loop and treat tools as an afterthought: hand-written wrappers, prompts that describe business rules, and code that grows with every new use case. The Model Context Protocol (MCP) changes the economics. Tools become standard, discoverable servers, and the business capabilities behind them already exist in your Application Programming Interfaces (APIs). The HAPI MCP stack starts from that observation: an agent is only as reliable as the capabilities it receives, and the best source of capabilities is a well-described API contract.

This guide shows you how to build and manage an MCP-based agent without writing tool code. You define capabilities in OpenAPI 3.x contracts, compose them with intent-based planning and Arazzo 1.1 workflows, and serve them as MCP tools with the HAPI Command Line Interface (CLI). You then give the agent a transparent harness with OrcA in Visual Studio Code (VS Code), test and measure it, deploy the server, and manage it over time. At the end of this guide, you have a repeatable process that turns any API you own into a governed set of agent capabilities, ready for any MCP client and for role-based teammates such as Clooney from Clawne Me.

Key Takeaways​

This section answers the main question of this guide in five statements.

  • An MCP-based agent has five parts: a model, a harness, tools, capability contracts, and a role.
  • HAPI serves OpenAPI 3.x and Arazzo 1.1 contracts as MCP tools, so you build agent tools without writing tool code.
  • Intent-based planning composes atomic capabilities on demand; Arazzo workflows keep sequences that must never change.
  • OrcA is the harness in VS Code: it loads tools progressively, enforces approvals, and records every exchange in Traffic.
  • Fix the contract, not the prompt, and gate every contract change with hapi graph audit in CI.

Prerequisites​

Before you begin, you need:

  • An OpenAPI 3.x contract for an API you own, with stable operationId values. An Arazzo 1.1 document is optional.
  • The HAPI CLI version 1.2 or later. Run hapi --version and hapi plugins list to confirm the Capability Graph and Arazzo plugins are installed.
  • VS Code with the OrcA extension and a configured chat model, either a VS Code language model or an API key for a supported provider.
  • Working knowledge of YAML and of OpenAPI operations, responses, and security schemes.
nota

The examples use a fictional clinic appointments API with the operations searchProfessionals, getAvailability, bookAppointment, listPatientAppointments, and cancelAppointment. Replace them with the operations of your own domain.

Understand the Anatomy of an MCP-Based Agent​

This section breaks an agent into its parts, so you know which part each step of this guide builds and who owns it.

An agent is not one program. Five parts cooperate, and each one fails in its own way:

PartResponsibilityIn the HAPI MCP stack
ModelUnderstands the request and proposes the next actionAny LLM; OrcA supports VS Code language models and API-key providers
HarnessPrepares instructions, context, and tool definitions; applies approvals; routes tool calls; records what happenedOrcA in VS Code, or the harness of your agent platform
ToolsPerform actions on real systemsMCP servers that HAPI serves from your contracts
Capability contractsDescribe what each action does, when it applies, and what it requiresOpenAPI operations with x-hapi-* metadata, plus Arazzo workflows
RoleNarrows the agent to a job: instructions, goals, and a subset of toolsA configured assistant, such as a Clooney receptionist or support role

The reasoning loop runs in the harness:

  1. The harness sends the instructions, the conversation, and the tool definitions to the model.
  2. The model answers or asks for a tool call.
  3. The harness checks approvals, calls the tool, and returns the result.
  4. The model decides whether to call another tool, ask the user a question, or answer.

Frameworks that rely on the loop alone push business rules into prompts, where the model can forget or reinterpret them. The HAPI MCP stack keeps the loop but moves the rules into the contract, where a deterministic engine enforces them. The model still reasons; it reasons within boundaries that the contract defines.

Define Capabilities in Your API Contracts​

This section shows you how to turn API operations into well-defined capabilities, which is the only step that requires design effort.

A capability is one business action with a clear purpose, clear inputs, and a clear effect: search professionals, book an appointment, cancel an appointment. In the HAPI MCP stack, each OpenAPI operation is a capability, and its description is the tool definition the model reads.

  1. Give each operation one responsibility, a stable verb-first operationId, and a summary in the language of your users.

    paths:
    /appointments:
    post:
    operationId: bookAppointment
    summary: Book an appointment for the patient
    description: |
    Books a confirmed appointment in the selected professional's free slot.
    Use the `slotId` returned by getAvailability; a constructed value returns `400`.

    The operationId becomes the tool name. The summary and description drive tool search, so precise wording replaces prompt instructions.

  2. Declare when the capability applies and what it changes.

          x-destructiveHint: false
    x-hapi-capability: [Healthcare/Appointments/Booking]
    x-hapi-intent:
    use-when:
    - The patient selected a professional and a free slot and confirmed the details.
    avoid-when:
    - The patient wants to move an existing appointment.
    x-hapi-effects:
    mode: create
    side-effecting: true
    destructive: false
    idempotent: false
    requires-confirmation: true

    Intent separates similar capabilities. Effects add a confirmation gate that no prompt can skip.

  3. Declare what must be true before the capability runs and what is true after.

          x-hapi-planning:
    requires:
    - predicate: patient.identity.verified
    - predicate: professional.selected
    - predicate: slot.selected
    - predicate: appointment.details.confirmed
    produces:
    - predicate: appointment.booked

    These facts turn the capability into an atomic transition that a planner can combine with others.

Apply these rules to every capability:

  • Single responsibility. Separate searches from selections and selections from changes.
  • Explicit inputs. Describe where each parameter value comes from, such as "the slotId returned by getAvailability."
  • Meaningful failures. Return business status codes, such as 409 for a taken slot, and describe the next step in the response description.
  • Documentation as interface. The description is what the model reads; write it for the reader who decides what to do next.

For the complete set of metadata, including client facts and failure outcomes, follow How to Design OpenAPI Contracts That Guide AI Agents.

Compose Capabilities Without Hard-Coding Behavior​

This section shows you the three ways to combine capabilities, and when to use each one.

Hard-coded agents fail because they predict every path in advance. Composition in the HAPI MCP stack happens at three levels:

  • Intent-based planning. Atomic capabilities declare the facts they require and produce. The HAPI Capability Graph (HCG) computes the route from the current verified state to the user's goal, and recomputes it when the state changes. Use it for conversations with choices, confirmations, and failures.
  • Arazzo workflows. A fixed sequence that must always run together, such as booking an appointment and sending the confirmation, becomes one Arazzo workflow. HAPI serves it as one MCP tool, and a workflow with x-hapi-planning becomes one atomic step in a plan.
  • Composed contracts. Several APIs, such as flights, hotels, and transfers, combine through Arazzo source descriptions or a composed OpenAPI façade that the capability graph compiles.

Composition through contracts keeps capabilities loosely coupled. A new capability joins existing plans as soon as its facts connect to them, without changes to the agent.

aviso

Arazzo workflows are not transactions. A failure in a later step leaves the changes of earlier steps in place, and a workflow is idempotent only when every step is. Design compensation explicitly. How to Make Intent-Based Contracts and APIs AI-Ready covers this trade-off in detail.

Serve Capabilities as MCP Tools with HAPI​

This section shows you how to expose the contract as an MCP server and choose how much guidance the server gives the agent.

  1. Preview the tools without starting a server.

    $ hapi serve --specs ./clinic.openapi.yaml --mcp --dry-run --output table

    The dry run lists every tool HAPI generates from the contract. Use --output markdown to produce a system prompt template for an agent.

  2. Serve the contract with progressive discovery and planning.

    $ hapi serve --specs ./clinic.openapi.yaml --mcp --capability-graph --capability-planning --port 3000

    HAPI compiles the capability graph, defers the operation tools behind a tool_search tool, and adds the read-only capability_context and capability_plan tools. The agent loads only the tools it needs, and plans never call your API.

  3. Serve an existing backend without a local implementation.

    $ hapi serve --specs ./clinic.openapi.yaml --headless --url https://api.example.com --capability-graph --capability-planning

    Headless mode exposes only the MCP endpoint and forwards each tool call to the backend at --url. The API stays where it is; the contract becomes the integration.

  4. Serve an Arazzo document as workflow tools.

    $ hapi arazzo validate ./clinic.arazzo.yaml --strict
    $ hapi arazzo serve ./clinic.arazzo.yaml --mcp --port 3001

    Strict validation fails when a workflow's planning facts disagree with its steps, so inconsistent workflows never reach an agent.

Give the Agent a Harness with OrcA​

This section shows you how OrcA prepares each request, keeps the context small, and enforces approvals while you build and test the agent.

OrcA is a specialised harness for MCP and API work. It does not edit files or run a terminal; it connects models to MCP servers and shows every exchange.

  1. Connect the server.

    In the MCP Servers view, select Add External MCP Server…, enter a name such as clinic and the URL http://localhost:3000/mcp, and connect. For a contract in your workspace, select Run with HAPI in the editor title bar instead. OrcA stores header values, such as API keys, in VS Code secret storage.

  2. Confirm that progressive discovery is active.

    Hover over the server. The tooltip shows a Discovery line, such as "Progressive tool discovery: tool_search (8 of 11 tools deferred) · Capability graph: capability_context, capability_plan".

  3. Write the agent's instructions in the Harness tab.

    The tab shows your instructions, the guidance OrcA adds automatically, and a token preview per server that compares the tools sent upfront with the full catalog. Save instructions for your user profile or for the workspace.

  4. Set the approval and discovery policies.

    SettingDefaultEffect
    orca.chat.confirmToolsmutatingAsks before any tool that is not read-only.
    orca.chat.toolDiscoveryautoDefers tools on servers that offer search; always applies local search to every server.
    orca.chat.toolPrefetchtrueLoads matching tools and capability context before the model answers each message.
    orca.chat.maxToolRounds8Limits the tool calls in one turn.

Test and Iterate on Agent Behavior​

This section shows you how to test the agent offline and in conversation, and how to turn each failure into a contract fix.

  1. Test the plans offline with the HAPI CLI.

    $ hapi graph compile ./clinic.openapi.yaml --out clinic.graph.json
    $ hapi graph audit clinic.graph.json
    $ hapi graph simulate clinic.graph.json --initial-fact patient.identity.verified --goal-fact appointment.booked

    The audit exits with code 1 when a requirement has no source or a goal is unreachable. The simulation returns clarification-required until the patient makes the missing choices, which proves the agent asks instead of guessing.

  2. Test a multi-step conversation in OrcA.

    Find a pediatrician next Tuesday afternoon, then book the first free slot.

    Chat cards show which tools OrcA loaded for each message. The Context tab shows the goal, the required facts, and the gates for the request.

  3. Inspect each exchange in the Traffic view.

    Traffic records every model round and tool call with its latency, size, tokens, and cost, and links each tool call to the round that caused it. Use Replay… to repeat a call, Compare Selected to compare two responses, and Open Operation in Contract to jump to the operation behind a tool.

  4. Fix the contract, not the prompt.

    When the agent picks the wrong tool, improve the summary or x-hapi-intent. When it guesses a choice, declare the choice as a client fact. When it retries a failure, add an x-hapi-outcome. Each fix applies to every agent that uses the contract.

Deploy the MCP Server​

This section shows you how to move the server from your machine to an environment that other agents can reach.

  1. Deploy the contract to Cloudflare Workers.

    $ hapi deploy --specs https://api.example.com/openapi.yaml --url https://api.example.com --capability-graph --capability-planning

    The Worker runs in headless mode and reads the contract from an HTTPS URL. Run the command with --dryRun first to print the planned actions without executing them.

  2. Deploy from VS Code.

    In OrcA, select Deploy MCP Server on a contract to run the same deployment from the editor, or configure a deployment hook in the orca.deploy.scripts setting for your own pipeline.

  3. Register the server with other MCP clients.

    Select Add to VS Code MCP Servers to make the server available to other agents in VS Code. Use Expose via Proxy when you want OrcA to record the traffic of another MCP client.

Manage the Agent Lifecycle​

This section shows you how to keep capabilities reliable as contracts, models, and roles change.

  • Version contracts deliberately. Keep operationId values stable; a renamed operation breaks saved plans and conversations. The capability graph fingerprint changes whenever planning metadata changes, which gives you a reliable signal for review.
  • Gate changes in Continuous Integration (CI). Run hapi graph audit and hapi arazzo validate --strict on every pull request. Both exit with code 1 on gaps.
  • Measure context and cost. Compare the token preview in the Harness tab before and after each contract change, and track cost per conversation in Traffic.
  • Watch operational events. The Activity tab records connections, new chats, and failures with a plain explanation of which service failed and why.
  • Assign roles on top of shared capabilities. A receptionist role and a support role can share one contract with different instructions and goals. Clooney, the AI teammate from Clawne Me, follows this pattern: one clone takes different roles, and each role relies on the same well-described capabilities.

Troubleshoot MCP-Based Agents​

This section maps common agent symptoms to the part of the stack that fixes them.

SymptomPart to fixFix
The agent says a tool is unavailable.ContractImprove the summary and description; confirm the tool appears in the OrcA catalog.
The agent loads too many tools.ServerServe with --capability-graph or --deferred-tool-search.
The agent picks a choice for the user.ContractProduce a consultation fact from searches and declare selections as client facts.
Every search asks for approval.ContractAdd x-readOnlyHint: true to read-only POST operations.
The agent retries a failed booking.ContractAdd x-hapi-outcome and a response description that names the next question.
Plans always return clarification-required.ContractRun hapi graph audit and declare x-hapi-client-facts.
A workflow appears as a tool but not in plans.WorkflowRemove nested workflows and dynamic branches, then validate with --strict.

Frequently Asked Questions​

This section answers the questions readers ask most often about this topic.

What Is an MCP-based Agent?​

An MCP-based agent is a Large Language Model that runs in a loop inside a harness and acts through Model Context Protocol (MCP) tools. In the HAPI MCP stack, the tools come from your OpenAPI and Arazzo contracts, the harness is OrcA or your agent platform, and a role narrows the agent to a job.

Do I Need to Write Code to Give an Agent Tools from My API?​

No. HAPI reads an OpenAPI 3.x or Arazzo 1.1 contract and serves each operation or workflow as an MCP tool. With --headless --url, HAPI forwards each tool call to your existing backend, so the contract is the whole integration.

What Is an Agent Harness, and What Does OrcA Do?​

A harness prepares the instructions, context, and tool definitions for the model, applies approvals, routes tool calls, and records what happened. OrcA is a VS Code harness for MCP and API work: it connects models to MCP servers, loads tools progressively, asks before tools that are not read-only, and shows every exchange in its Traffic view. It does not edit files or run a terminal.

How Do I Stop an Agent from Loading Too Many Tools?​

Serve the contract with --capability-graph or --deferred-tool-search. HAPI defers operation tools behind a tool_search tool, and OrcA loads only the tools each message needs, while listing the names of the rest so the model knows they exist.

How Do I Test an MCP Agent Before Production?​

Test plans offline with hapi graph audit and hapi graph simulate, then test conversations in OrcA. The Context tab shows goals, required facts, and gates, and the Traffic view shows each model round and tool call with latency, tokens, and cost.

How Do I Deploy an MCP Server Built from an OpenAPI Contract?​

Run hapi deploy with an HTTPS contract URL and your backend URL to deploy a headless MCP server to Cloudflare Workers, or select Deploy MCP Server on the contract in OrcA.

Conclusion​

You built an MCP-based agent from capabilities you already own. You defined capabilities as OpenAPI operations with intent, effects, and planning facts, composed them through intent-based planning and Arazzo workflows, and served them as MCP tools with HAPI. You gave the agent a transparent harness with OrcA, tested it offline and in conversation, deployed the server, and set up the practices that keep it reliable over time.

The model reasons, the harness governs, and the contract defines what is possible. Continue with How to Design OpenAPI Contracts That Guide AI Agents for the full metadata reference, and with How to Make Intent-Based Contracts and APIs AI-Ready for the trade-offs between workflows and intent-based planning.