When building AI tools, when to call APIs directly vs. wrap an MCP layer: a practical three-layer integration decision

Summary: Using APIYI image generation as an example, this explains whether a deterministic program, a single Agent, or multiple hosts should call the API directly, add a Skill, or wrap it in an MCP layer.

When you’re building AI tools, a deterministic program can call the API directly over HTTP or an SDK—that’s the simplest case. If a single Agent repeats the same set of steps, you can put the existing script and execution rules into a Skill; no separate service deployment is needed. Only when the team genuinely needs multiple Agent clients (for example, Codex and Claude Code) to discover and invoke the same capability is it worth maintaining an MCP service.

These three layers build on one another. An MCP tool still ultimately calls that already-validated direct API client, and the Skill is also driving the same script. Whether to add a layer on top depends on three conditions: whether multiple hosts need to share it, whether side effects can be controlled, and whether the team is willing to maintain an extra runtime.

when-to-call-api-directly-vs-wrap-mcp-en-image-0

Knowledge map: how the three layers—direct API, Skill, and MCP—divide up

The table below lists the three integration layers, their triggers, and what you need to maintain, with numbers that correspond to later sections. Read in order from 1 to 4: the API client you build in Section 1 is reused by the script in Section 2; the MCP tool in Section 3 also calls it when it goes live; Section 4 pulls the decision criteria together. If you already have a plan, you can go straight to Section 4.

Layer Trigger What to maintain Acceptance criteria Section
Direct API Deterministic program, fixed input/output Auth, request and response conversion, per-call cost, failure handling PNG file correctly written to disk 1
Skill + script One Agent repeating a fixed workflow SKILL.md steps, script, approval checkpoints Preview, then approve; verify actual files and usage 2
MCP service Multiple hosts need dynamic discovery of the same tool Tool schema, process or address, permissions, error mapping, updates Inspector can list the tools; both hosts produce consistent output 3
Go-live decision Decide which layer to keep Shared-use needs, side effects, maintenance cost Clear answers to all three questions 4

The call relationships between the layers look like this:

Desktop app / web backend ──→ direct API client ──→ model gateway
Agent ──(reads Skill)──→ script ──→ direct API client
Host A / Host B ──(MCP tool discovery)──→ MCP service ──→ direct API client

when-to-call-api-directly-vs-wrap-mcp-en-image-1

To Know: 8 terms for understanding API vs. MCP selection

Term Explanation
Direct API A program calls a business service over HTTP or through an SDK, then handles the returned result.
Model gateway An interface layer like APIYI that routes model requests to supported services and records usage.
Adapter Code that converts between your own input and an external model’s request, response, and error structures.
Host The AI client the user actually uses; it decides how MCP connections are loaded and authorized.
Tool discovery The host fetching tool names, descriptions, and input parameter definitions from a connected MCP server.
stdio A transport commonly used by local MCP, communicating through a process’s standard input and output.
Mock tool A stand-in used to verify tool discovery and parameter handling without actually hitting the business interface.
Side effect An external change caused by tool execution, such as uploading a file, charging a fee, or modifying data.

1 Fixed programs calling APIs directly: the simplest way to integrate AI tools

1.1 Requests and responses when calling an API directly

The scenario is very fixed: you feed in a prompt and a size, and you get back a PNG. A local Tkinter app or a web backend POSTs straight to the gateway’s /v1/images/generations, sets model to the platform-listed gpt-image-2.6-sunburst, and uses size=1024x1024, quality=medium, output_format=png to generate one image. The result is read from data[0].b64_json, decoded, and saved.

import base64
import os
import pathlib
import requests

API_BASE = "https://api.apiyi.com/v1"  # APIYI OpenAI-compatible gateway

def generate_png(prompt: str, out_path: str, size: str = "1024x1024") -> pathlib.Path:
    key = os.environ["APIYI_API_KEY"]  # credentials are injected only via backend env vars
    resp = requests.post(
        f"{API_BASE}/images/generations",
        headers={"Authorization": f"Bearer {key}"},
        json={
            "model": "gpt-image-2.6-sunburst",
            "prompt": prompt,
            "size": size,
            "quality": "medium",
            "output_format": "png",
        },
        timeout=300,
    )
    resp.raise_for_status()
    b64 = resp.json()["data"][0]["b64_json"]
    path = pathlib.Path(out_path)
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_bytes(base64.b64decode(b64))
    return path

1.2 Calling this function straight from a local UI

A Tkinter button callback can call generate_png directly. To keep the UI from freezing, it’s best to run it in a background thread. For web scenarios, the backend route calls this function, and the frontend just submits the prompt and gets back an image URL. That way the key never shows up in frontend code or in output files.

One thing to watch: this endpoint is synchronous. If the request goes out and no response comes back, you can’t recover the result with a task_id. So handle failures carefully: log the request parameters and timestamp first, then decide whether to retry, so you don’t submit the same image twice.

1.3 What this direct-API layer is responsible for

The responsibilities here are clear:

  • HTTP auth: inject the Bearer credential on the backend.
  • Request and result conversion: turn the prompt and size into a request body, and turn Base64 into a file.
  • Per-call cost and failure handling: every call costs money, and timeouts and errors are up to the app.
  • Business rules: the upstream model doesn’t understand your local app’s product IDs and naming conventions, and where files go is decided by the app.

When there’s no need for multiple hosts to share anything, adding an MCP service on top just gives you another process or address to maintain, plus error conversion and permission config — no real benefit for this program.

Tip: Grab the free trial credit for new users at APIYI apiyi.com, run one image through the function above to confirm the parameters and response structure, and then decide whether it’s worth adding another layer.

2 When to Just Add a Skill or Script to an Agent Instead of Wrapping It in MCP

2.1 Scenarios Suited to Skills

Say the new requirement is this: have an Agent repeatedly generate covers following a brand prompt, a fixed file naming scheme, and a budget, then verify them before delivery. What really needs to be reused here is the workflow, not a new callable interface. You just write a SKILL.md that spells out the steps, decision conditions, and delivery format, while the script keeps handling the direct HTTP requests.

Per the Agent Skills spec, a Skill is usually a directory containing a SKILL.md with YAML frontmatter. The name and description in the frontmatter say what it is and when to use it; the directory can also hold scripts, references, and assets. Skills load on demand: normally only a short discovery blurb is exposed, and the full steps are read only once the Skill is selected.

2.2 An Executable SKILL.md Example

The render_cover command below is a sample script built by the team, which reuses generate_png from Section 1 internally.

---
name: render-cover
description: Generate product cover images according to brand guidelines. Use when the user asks to generate or batch-generate covers.
---

## Steps
1. Confirm the parameters: product ID, prompt, size. If any of them is missing, ask the user.
2. Run `scripts/render_cover --preview`, which outputs the model, size, and estimated billing channel.
3. Only after the user explicitly confirms, run `scripts/render_cover --run`.
4. Check that `<product ID>_cover.png` actually exists in the output directory.

## Delivery Format
- Actual file path
- Model and size used
- Model usage for this run
- Items not completed or not verified

This Skill inserts a confirmation checkpoint between “preview” and “actual execution” — user approval is required before any charges. The naming rules and acceptance criteria live in the Skill and are carried out by the Agent, with no extra service to deploy.

2.3 Prerequisites for a Skill to Take Effect

A Skill is just text and files. The model is only actually invoked when the host provides an environment for running scripts and has already authorized script execution. Claude Code Skills can match automatically or be invoked explicitly with /name, and the trigger method can be restricted through configuration; Codex’s public guide likewise describes both explicit invocation and Agent-driven matching. Also note: writing a Skill name so that it looks like a tool doesn’t turn that workflow text into a server-side API.

APIYI provides an onboarding Skill (docs.apiyi.com/skill.md) that lays out models, authentication, endpoints, and troubleshooting notes — useful reference material when writing your scripts. But that Skill and the key used for actual calls are two separate configurations: installing the Skill doesn’t automatically grant invocation permissions, and the key the script uses has to be set up separately on APIYI apiyi.com and injected via environment variables.

3 Which Requirement Comes First: When It’s Worth Wrapping an MCP Layer Around Your AI Tool

3.1 The signal: two hosts need to call the same tool

When some people on the team use Codex and others use Claude Code, and all of them want to call the same “generate an image request” capability, a Skill is no longer enough. Two reasons: sharing a directory doesn’t guarantee that script dependencies, tool names, permissions, and host extension fields will port over cleanly; and every host has to be able to get a consistent tool name and parameter definition through tool discovery. That’s exactly the connection problem MCP is built to solve.

In MCP’s architecture, the host is the software the user actually interacts with, the client establishes a connection to a given server, and the server can expose tools, resources, and prompts. A local MCP server doesn’t have to touch the internet — a process the host launches over stdio is enough to provide local tools.

3.2 Building a minimal offline stdio server

Start by validating the protocol with a mock tool, before wiring up anything real. This tool only echoes back its parameters — it doesn’t read files and it doesn’t cost money. Create a small standalone project and, inside a virtual environment, install the dependency the way the official MCP Python SDK v1 expects:

python -m pip install "mcp>=1,<2"

Name the source file server.py:

from mcp.server.fastmcp import FastMCP

server = FastMCP("image-request-demo")

@server.tool()
def describe_image_request(prompt: str) -> dict:
    """Preview fields for an image generation request without submitting it."""
    if not prompt.strip():
        raise ValueError("请输入产品图片描述")
    return {
        "mode": "mock",
        "would_submit": False,
        "model": "gpt-image-2.6-sunburst",
        "size": "1024x1024",
        "prompt": prompt,
    }

if __name__ == "__main__":
    server.run(transport="stdio")

3.3 Verify tool discovery with MCP Inspector

First check the Inspector docs to confirm your Node version meets the requirements, then run it with the absolute path to the Python interpreter in your virtual environment:

npx @modelcontextprotocol/inspector --cli <python绝对路径> <server.py绝对路径> --method tools/list

The response should list the tool named describe_image_request. Then use the Inspector’s call panel to pass in prompt=一张留白的白瓷杯占位图; the returned value should include mode=mock and would_submit=false. What you’re validating here is protocol communication and parameter constraints — no model invocation involved at all.

3.4 Register the same server in both Codex and Claude Code

The same local server can be registered with both hosts separately. If any path contains spaces, wrap it in quotes.

# Codex CLI
codex mcp add image-request-demo -- <python绝对路径> <server.py绝对路径>

# Claude Code
claude mcp add --transport stdio image-request-demo -- <python绝对路径> <server.py绝对路径>

Once the config takes effect in both tools, verify it step by step: first confirm the host can list this tool, then ask it to call only this preview tool, and finally compare the two outputs — the fields should match exactly. Only when you’ve gotten this far have you proven that the “multiple hosts sharing one capability” requirement actually holds.

when-to-call-api-directly-vs-wrap-mcp-en-image-2

4 Three Questions to Ask Before Launch: Keep the Direct API, or Wrap It in an MCP Layer

4.1 The Three Decision Questions

Question If the answer is “no” If the answer is “yes”
Does the same action need to be dynamically discovered by multiple hosts? A single program calls the API directly; a single Agent plus a Skill Move on to the next question
Can the business action be reused with a well-defined structure and set of permissions? Nail down the parameters and permissions first, and hold off on MCP Move on to the next question
Is the team willing to maintain an extra runtime? Fall back to Skill + scripts, with each host integrating on its own Keep the MCP layer

The extra maintenance work includes tool schemas, host connections, version updates, error handling, and permissions. These costs depend on the specific host and server implementation — there’s no universal fixed number. A more reliable approach is to implement both options for the same task, then compare the length of the Skill text, the number of tool calls, and the actual bill.

4.2 Which Layers to Separate When Running MCP Tools in Production

If the production MCP service exposes real generation tools, the tool layer should call the direct API client that was already validated before launch, rather than writing a fresh set of request logic. Before launch, you need to spell out the following:

  • State distinctions: Previewed parameters, real request sent, result received, and saved successfully — these four states should be returned separately.
  • Allowlist: Accept only the models and sizes that are permitted.
  • Account and limits: Agree on which account the Key belongs to, what the request cap is, and who’s allowed to submit.
  • Logging: Keep the request ID and usage.
  • Response body: Don’t stuff a whole Base64 blob into the Agent’s context window — return a controlled file path or reference instead.

4.3 Distinguishing APIYI’s Existing Capabilities from Your Team’s Own

What APIYI currently makes public is a docs MCP (docs.apiyi.com/mcp) and an integration Skill. On November 23, 2026, we ran a keyless JSON-RPC validation: initialize, tools/list, and resources/list all read fine, and the negotiated version was 2025-11-25. The tool list includes documentation search, reading documentation, and submitting feedback; the resource list contains a plain Markdown resource at mintlify://skills/apiyi, and the public interface doesn’t declare the MCP Skills Beta extension.

These tools are for looking up platform documentation and integration information. Details such as which models a given Key can actually see, the account balance, and invocation charges all come from separate credentials or endpoints. Documentation search sometimes returns model pages with similar names, so the authoritative model ID should be taken from the public registry docs.apiyi.com/model-registry.json. The describe_image_request and render_cover examples in this article are built by the team — they aren’t tools the platform provides.

Selection tip: Before deciding whether to wrap things in MCP, you can first get the direct API client working against the unified APIYI apiyi.com interface, so that both the Skill and the MCP layer can reuse that client — you maintain authentication and parameters in one place.

Let One Acceptance Run Decide Which Layer to Keep

Here’s the approach: first use the function from Section 1 to generate a real image, then use the mock tool from Section 3 to invoke it once in each of the two hosts. If only one program or one Agent will use it, stop at the direct API or Skill layer. If both hosts genuinely need the same tool, and the team is willing to take on maintaining schemas, permissions, and updates, then replace the mock tool with a production tool that calls the real client.

We recommend starting with free credits from APIYI apiyi.com to validate the first layer, then using actual invocation data to decide which layer is worth adding.

References

  1. APIYI Documentation Center: Image API, developer kit, Skill integration, documentation MCP, and model registry

    • Link: docs.apiyi.com
    • Note: Relevant paths include /api-capabilities/gpt-image-2/gpt-image-2-6, /api-capabilities/image-api-best-practices, /developer-kit, /skill.md, /mcp, and /model-registry.json; checked on 2026-11-23
  2. MCP Official Architecture and Introduction: division of responsibilities among host, client, and server, plus tools, resources, and prompts

    • Link: modelcontextprotocol.io/docs/learn/architecture
  3. MCP Inspector Official Guide: tool discovery and invocation in CLI mode

    • Link: modelcontextprotocol.io/docs/tools/inspector
  4. MCP Official Python SDK v1: FastMCP examples

    • Link: github.com/modelcontextprotocol/python-sdk/tree/v1.x
  5. Agent Skills Specification: directory structure, required metadata, and on-demand loading

    • Link: agentskills.io/specification
  6. OpenAI Codex CLI MCP Configuration: registration, transport, and authorization for MCP services

    • Link: learn.chatgpt.com/docs/extend/mcp
  7. Anthropic Claude Code MCP and Skills: stdio service registration and Skill triggering

    • Link: code.claude.com/docs/en/mcp

Author: APIYI Technical Team
Technical Inquiries: You’re welcome to contact us through the APIYI website homepage. For more integration resources, see the docs.apiyi.com documentation center.

Leave a Comment