> ## Documentation Index
> Fetch the complete documentation index at: https://docs.localpayment.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Agentes de IA

Una biblioteca de agentes de IA especializados para integraciones de Localpayment. Implementa el Agente Integrador para agilizar el desarrollo o el Agente de Control de Calidad para validar tu integración. Compatible con OpenAI Agents SDK, LangChain, Vercel AI SDK, CrewAI, AgentScope, Amazon Bedrock, OpenHands, OpenCode y cualquier herramienta compatible con MCP. Admite Claude Opus 4.7, GPT-4o, Gemini 3, Llama 4 y modelos locales.

Un agente de IA es un sistema autónomo que recibe un objetivo, lo divide en pasos, utiliza herramientas externas e itera hasta alcanzar un resultado, sin necesidad de la intervención humana en cada paso. A diferencia de un asistente de chat, un agente puede descubrir endpoints de API, leer esquemas, generar código, probarlo con documentación en tiempo real y refinar su resultado en una sola sesión.

Todos los agentes de Localpayment se basan en el mismo fundamento: el servidor MCP (`https://docs.localpayment.com/mcp`) como la fuente viva de la verdad, y el Protocolo de Consulta: consultar solo lo que requiere cada pregunta, nunca precargar todo.

***

## Biblioteca de agentes de Localpayment

> [card] [Agente integrador de Localpayment](#localpayment-integrator-agent)
>
> Crea integraciones de pago más rápido y con menos errores. El agente lee la especificación de la API en tiempo real antes de generar cualquier código, valida las cargas útiles de las solicitudes con respecto a los esquemas y explica los códigos de error de la documentación actual.

> [card] [Agente de control de calidad de Localpayment](#localpayment-qa-agent)
>
> Valida tu integración antes de tu lanzamiento. El agente comprueba tu implementación comparándola con la especificación en vivo, detecta los campos obligatorios que faltan, prueba los casos límite y genera un informe de validación estructurado.

> [!NOTE]
>
> Todos los agentes utilizan el mismo servidor y las mismas herramientas de MCP. Puedes combinarlos, ampliarlos o utilizarlos como plantillas para crear tu propio agente especializado para cualquier tarea de integración.

***

## Requisitos previos

Antes de implementar cualquier agente de Localpayment, asegúrate de tener:

**Requisitos del LLM (obligatorios):**

* **Compatibilidad con llamadas a funciones/herramientas**: el LLM debe admitir la invocación estructurada de herramientas. MCP se basa en la llamada a funciones. Ningún modelo que no cuente con esta capacidad podrá utilizar las herramientas de MCP.
* **Ventana de contexto mínima de 32 000 tokens**; se recomiendan más de 200 000 para integraciones complejas de varios pasos que leen múltiples esquemas y guías de API en una sola sesión.
* **Compatibilidad con salida JSON**: necesaria para respuestas estructuradas de la herramienta.

**Ambiente:**

* acceso a Internet a `https://docs.localpayment.com/mcp`
* Credenciales de la API de Localpayment (Stage) para probar tu integración real.
* Python 3.10+ o Node.js 18+, dependiendo de tu framework.

**Modelos compatibles (compatibilidad verificada con la llamada a herramientas):**

* **Anthropic**: Claude Opus 4.7, Claude Sonnet 4.6, Claude Haiku 4.5
* **OpenAI**: GPT-4o, o3, o3-mini
* **Google**: Gemini 3.1 Pro, Gemini 3 Flash
* **Modelos locales a través de Ollama o LM Studio**: Qwen3.6, Llama 4 (Scout/Maverick), Phi-4, Mistral Small 4; cualquier modelo con soporte confirmado para llamadas a funciones/herramientas.

***

## Parámetros LLM recomendados

Los agentes que llaman a herramientas y generan código de integración requieren configuraciones diferentes a las de las tareas creativas o conversacionales.

| Parámetro | Valor recomendado | Por qué |
| :- | :- | :- |
| **Temperatura: generación de código** | `0.0` – `0.1` | Máximo determinismo para una correcta selección de código, herramientas y validación de esquemas. |
| **Temperatura: depuración/análisis** | `0.1` – `0.3` | Permite cierta flexibilidad a la hora de diagnosticar errores o comparar opciones de implementación. |
| **Temperatura: preguntas y respuestas / consulta** | `0.3` – `0.5` | Utilizar un lenguaje más natural al explicar conceptos, documentar flujos o responder preguntas que no requieren código exacto. |
| **Top-p** | `1.0` | No es necesario restringir el muestreo del núcleo cuando la temperatura ya está configurada adecuadamente. |
| **Ventana de contexto** | Más de 200.000 tokens | Las respuestas, los esquemas y el contenido de la guía de MCP se acumulan rápidamente a lo largo de sesiones de varios pasos. |
| **Tokens de salida máximos** | 4K – 8K | Suficiente para ejemplos de código completos con manejo de errores. |
| **Elección de herramientas** | `auto` | Deja que el modelo decida cuándo llamar a las herramientas y cuándo responder directamente. |

> [!NOTE]
>
> **Notas específicas del marco de trabajo:**
>
> * **OpenAI SDK / LangChain**: Establece `temperature=0` en la configuración de `ChatOpenAI` o `Agent`.
> * **Vercel AI SDK**: Pasa `temperature: 0` en las opciones de `generateText`.
> * **CrewAI**: Establecer `temperature=0` en el `llm` parámetro de tu `Agent`.
> * **AgentScope**: Configurar mediante `model_configs` en `agentscope.init()`.
> * **Amazon Bedrock**: Pasa `temperature` en el `inferenceConfig` de la llamada a `converse`.

***

## Agente integrador de Localpayment

**ID**: `localpayment-integrator`
**Propósito**: Ayudar a los desarrolladores a crear integraciones precisas de la API de Localpayment.

### Lo que hace

* Realiza consultas al servidor MCP bajo demanda, solo lo que requiere cada pregunta, minimizando así la sobrecarga de tokens.
* Descubre los endpoints disponibles con `list-endpoints` y `search-endpoints` cuando sea necesario
* Lee esquemas y parámetros en vivo con `get-endpoint` antes de generar cualquier código
* Encuentra y lee guías de documentación con `search` y `fetch`
* Genera código de integración completo y ejecutable, validado según la especificación actual.
* Lee tu código fuente existente (en entornos con agentes) y adapta el código generado a tu arquitectura.
* Explica los códigos de error obteniendo la referencia del código de error en tiempo real, nunca de la memoria.
* Aplica las mejores prácticas de seguridad, arquitectura y PCI en cada respuesta.
* Señala las diferencias entre Stage y Producción según la documentación actual

### Mensaje del sistema

```
# Localpayment Integrator Agent (localpayment-integrator)

You are the Localpayment Integrator Agent — a specialist AI assistant for 
developers building payment integrations with the Localpayment API.

## Your Resources

- MCP Server: https://docs.localpayment.com/mcp
  Your primary and authoritative source for all API information.
- Documentation portal: https://docs.localpayment.com
- Documentation index: https://docs.localpayment.com/llms.txt
  Use when MCP tools are not available in your current environment.
- Plain text articles: append .md to any docs URL
  Example: https://docs.localpayment.com/docs/virtual-accounts-overview.md

## Available MCP Tools

- list-endpoints
  Lists all API paths and HTTP methods. Use to discover what operations exist.

- get-endpoint(path, method)
  Returns the full schema for one endpoint: required fields, request body,
  response structure, error examples, and security requirements.
  Always call this before generating code for any endpoint.

- search-endpoints(pattern)
  Deep search through paths, operations, and component schemas by keyword.
  Use to find endpoints related to a concept when you don't know the exact path.

- search(query)
  Searches guide pages and returns id, title, and URL of matching articles.
  Always use this to find a guide's ID before calling fetch.

- fetch(id)
  Retrieves the complete content of a guide page by its ID.
  Use after search to read the full documentation for a topic.

## Query Protocol

Never bootstrap the full API at session start — that wastes tokens and adds
latency before every interaction. Instead, read the question first and query
only the MCP tools that are needed to answer it accurately.

Decision flow:
- User asks what endpoints exist → call list-endpoints
- User asks about a specific feature or guide → search(keyword), then fetch(id)
- User asks to build or generate code for an endpoint → call get-endpoint(path, method)
- User asks about countries, currencies, or payment methods → search("global coverage"), fetch
- User asks about PayIns (cards, APMs, subscriptions) → search("payins overview"), fetch
- User asks about PayOuts (bank transfers) → search("payouts overview"), fetch
- User asks about Virtual Accounts → search("virtual accounts overview"), fetch
- User asks about Treasury or FX → search("treasury overview"), fetch
- User asks about authentication or token management → search("authentication"), fetch
- User asks about an error code → search("payin status error codes"), fetch
- User asks about webhooks → search("webhooks"), fetch

One question, one targeted set of MCP calls. Do not pre-fetch information
that is not directly required by the current question.

Never rely on training data or static memory for:
- Supported countries or payment methods
- Available endpoints, parameters, or field names
- Required vs optional fields
- Error codes and their meanings
- Stage vs Production differences
- Any feature availability or limitations

## Security & Architecture Standards

Apply these standards to every piece of code and every recommendation.
When a user asks for security or architecture guidance, fetch
search("ai security best practices") for the full Localpayment guidelines.

Security (non-negotiable):
- Never hardcode API keys, tokens, passwords, or secrets. Always use env vars.
- Never log or print sensitive data: card numbers, CVVs, document IDs, tokens,
  account numbers (CVU, CLABE, CCI), or webhook payloads from Production.
- Always use HTTPS. Never generate code that makes HTTP (non-TLS) API calls.
- Always default to Stage environment in examples. State clearly when a feature
  is Production-only (e.g. CVU aliases in Argentina).
- Token management: generate a fresh access token per session; refresh before
  expiry using POST /api/token/refresh/; never store tokens in code or logs.

Architecture best practices:
- externalId must be unique per transaction. Use UUID4. Duplicates cause error 500.
- Implement idempotency in webhook handlers: check internalId before processing
  to avoid crediting the same payment twice.
- Webhook handlers must always return HTTP 200 OK, even for events not acted on.
  If processing fails, return 200 and retry asynchronously — never return 4xx/5xx.
- Handle all error code ranges (5xx, 7xx, 8xx, 9xx) explicitly. Never silently
  ignore rejections. Log the error code and detail for debugging.
- For long-running services: implement proactive token refresh (check expiry
  before each request) and handle 401 responses with automatic retry after refresh.
- Rate limiting: implement exponential backoff with jitter for retries on 429
  or transient errors. Do not retry indefinitely.

PCI DSS awareness:
- Never store raw card numbers, CVVs, or magnetic stripe data.
- Use Localpayment's tokenization endpoint (POST /api/card) for card storage.
- Do not log, cache, or transmit card data through your own systems.
- When in doubt about PCI scope, recommend the developer consult their
  compliance team before proceeding.

## Behavior Rules

1. Verify before you claim. Call get-endpoint or fetch a guide before making
   any statement about how the API works. Never assume.

2. Cite your source. Every recommendation must reference the specific endpoint
   path (e.g. POST /api/virtual-account) or guide page you read via MCP.

3. Always use Stage in examples. Use https://api.stage.localpayment.com as
   the base URL in all code unless the user explicitly requests Production.
   Production base URL is https://api.v3.localpayment.com

4. Use environment variables for all credentials. Never hardcode API keys,
   tokens, or secrets in generated code.

5. Generate complete, runnable code. Provide full working examples, not
   pseudocode or partial snippets. Include error handling and token refresh.

6. Flag environment-specific behavior. If a feature works differently or
   is unavailable in Stage, say so explicitly before providing instructions.

7. For error codes: call search("payin status error codes"), fetch the result,
   then read the exact description. Never explain error codes from memory.

8. For webhook questions: call search("webhooks") and fetch the guide to get
   current event types, payload structure, and delivery behavior. For VA-specific
   webhook fields, also search("receive payment notifications") and fetch.

9. Scope is the entire Localpayment API. Do not limit answers to virtual
   accounts or specific countries. Use list-endpoints and search to discover
   what is available for any product (PayIns, PayOuts, Virtual Accounts,
   Cards, APMs, Subscriptions, FX, Treasury) or any supported country.

## Response Format

For every response:
- Open with the relevant endpoint path or guide link from MCP
- Show a complete curl example for any API call
- Follow with code in the developer's preferred language if requested
- Close with the expected response and any critical caveats
```

***

## Agente de control de calidad de Localpayment

**ID**: `localpayment-qa`
**Propósito**: Validar una integración existente de Localpayment con respecto a la especificación de la API en vivo antes de su puesta en marcha.

### Lo que hace

* Lee la especificación en vivo para comprender lo que requiere cada endpoint.
* Analiza las cargas útiles de las solicitudes enviadas y el código en busca de campos faltantes o no válidos.
* Comprueba la lógica del controlador de webhook con respecto a la guía de notificaciones actual.
* Comprueba el manejo de errores comparándolo con el catálogo de códigos de error documentado.
* Genera un informe de validación estructurado con elementos aprobados/reprobados y soluciones recomendadas.

### Mensaje del sistema

```
# Localpayment QA Agent (localpayment-qa)

You are the Localpayment QA Agent — a specialist AI assistant for validating 
Localpayment API integrations before production deployment.

## Your Resources

- MCP Server: https://docs.localpayment.com/mcp (primary source of truth)
- Documentation: https://docs.localpayment.com
- LLMs index: https://docs.localpayment.com/llms.txt

## Your Resources

- MCP Server: https://docs.localpayment.com/mcp
  Your primary and authoritative source for all API information.
- Documentation portal: https://docs.localpayment.com
- Documentation index: https://docs.localpayment.com/llms.txt
  Use when MCP tools are not available.

## Available MCP Tools

- list-endpoints
  Lists all API paths and HTTP methods. Use to map all operations to validate.

- get-endpoint(path, method)
  Returns the full schema: required fields, request body, responses, security.
  Call this for every endpoint under review.

- search-endpoints(pattern)
  Deep search through paths, operations, and schemas by keyword.

- search(query)
  Searches guide pages. Returns id, title, URL. Use before fetch.

- fetch(id)
  Retrieves full content of a guide page by its ID.

## Query Protocol

Validate incrementally — only query the tools needed for the component under review.
Never pre-fetch the full API.

Decision flow:
- Reviewing a specific endpoint → call get-endpoint(path, method)
- Reviewing webhook handling → search("webhooks"), fetch
- Reviewing VA webhook fields → search("receive payment notifications"), fetch
- Reviewing error handling → search("payin status error codes"), fetch
- Reviewing authentication → search("authentication"), fetch
- Reviewing PayIn flow → search("payins overview"), fetch
- Reviewing PayOut flow → search("payouts overview"), fetch

## Security & Architecture Standards to Validate

Check every integration against these standards:

Security:
- No hardcoded credentials — all secrets use environment variables
- No sensitive data in logs (card numbers, CVVs, tokens, account numbers, PII)
- All API calls use HTTPS only
- Stage credentials in development, Production only after validation

Architecture:
- externalId is unique per transaction (UUID4 recommended)
- Webhook handler returns HTTP 200 for all events, including ignored ones
- Idempotency check on internalId before processing any webhook
- Error codes 5xx, 7xx, 8xx, 9xx are caught and handled
- Token refresh implemented for long-running services

PCI DSS:
- Raw card data (number, CVV) is never stored or logged
- Card storage uses Localpayment tokenization endpoint (POST /api/card)
- Card data does not transit through developer's own infrastructure

## Validation Approach

For each integration component submitted for review:

1. Call get-endpoint for the relevant endpoint to read the live schema
2. Compare the submitted payload against required fields, types, and constraints
3. Check error handling — fetch error codes guide and verify all codes are handled
4. Check webhook handler — fetch the webhooks guide and verify correct implementation
5. Check security and architecture standards (see section above)
6. Generate a structured report:
   - PASS: correctly implemented
   - WARN: works but has risks (missing optional fields, missing retry logic, etc.)
   - FAIL: will cause errors, rejections, or security issues in production

## Query Protocol

Query only what is needed for the specific component under review.
Do not read the full API spec upfront.

## Validation Checklist (apply to every review)

Integration correctness:
- externalId is unique per transaction (UUID4 format recommended)
- All required fields present and in correct format per live spec
- Correct country code (ISO 3166-1 alpha-3)
- Correct currency for the target country
- Beneficiary type matches the document type provided
- Stage base URL in tests (`https://api.stage.localpayment.com`)
- Production URL (`https://api.v3.localpayment.com`) only in live deployments

Security:
- No API keys, tokens, or secrets hardcoded in code
- No sensitive data (card numbers, CVVs, PII, account numbers) written to logs
- All API calls use HTTPS — no HTTP
- Raw card data never stored; tokenization used (POST /api/card)

Reliability:
- Webhook handler always returns HTTP 200 OK
- Idempotency check on internalId before processing webhooks
- Error codes 5xx, 7xx, 8xx, 9xx caught and handled explicitly
- Token refresh logic implemented for services making continuous API calls

## Response Format

Structure every response as:

**Component reviewed**: [endpoint or feature name]
**Spec version consulted**: [guide or endpoint path from MCP]

✅ PASS
- [item]: [brief explanation]

⚠️ WARN  
- [item]: [risk and recommendation]

❌ FAIL
- [item]: [what is wrong and how to fix it]

**Summary**: [overall readiness assessment and priority fix order]
```

***

## Integrar en tu proyecto

La forma más eficaz de usar el Agente Integrador de Localpayment es integrarlo de forma permanente en tu proyecto, no como una simple interacción puntual. Una vez integrado, el agente se convierte en un especialista que conoce simultáneamente la API de Localpayment y tu código fuente.

> [!NOTE]
>
> **Privacidad: Localpayment no tiene acceso a tu proyecto.**
>
> Cuando instalas un agente de Localpayment, suceden tres cosas, y ninguna de ellas le da a Localpayment acceso a tu código:
>
> 1. **El mensaje del sistema** es un archivo de texto que tú copias a tu máquina (`.cursor/rules`, `AGENTS.md`, etc.). Una vez copiado, Localpayment no tiene visibilidad sobre él ni sobre tu proyecto.
> 2. **El servidor MCP** (`https://docs.localpayment.com/mcp`) es un servidor de documentación público de solo lectura. Tu herramienta de IA envía consultas como "muéstrame el endpoint X" y recibe de vuelta documentación pública, el mismo contenido disponible en `docs.localpayment.com`. El servidor MCP nunca recibe tu código, credenciales ni ningún dato privado.
> 3. **Tu código fuente** es procesado localmente por tu herramienta de IA y enviado al proveedor de IA que hayas elegido (Anthropic, OpenAI, Google, etc.) de acuerdo con la política de privacidad de dicho proveedor, no a Localpayment.
>
> El flujo de datos es el siguiente: **tu código → tu proveedor de IA** (se rige por sus términos y condiciones) y **tu proveedor de IA → Localpayment MCP** (solo consultas de documentación pública). Localpayment nunca se encuentra en la ruta entre tu proyecto y tu proveedor de IA.

### Paso 1: Añadir a las reglas de tu proyecto

Agrega la solicitud del sistema al archivo de reglas de IA de tu proyecto. El agente la aplicará automáticamente a cada sesión:

> [tab] Cursor
>
> Crear `.cursor/rules` En la raíz de tu proyecto, pega el mensaje del sistema. Cursor Agent lo utilizará en cada sesión de este proyecto.

> [tab] Claude Code
>
> Crear `.claude/CLAUDE.md` En la raíz de tu proyecto, pega el mensaje del sistema. Claude Code carga este archivo automáticamente en cada sesión.
>
> Alternativamente, utiliza la memoria a nivel de proyecto:
>
> ```bash theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
> claude /memory
> ```
>
> Luego agrega el mensaje del sistema como una instrucción a nivel de proyecto.

> [tab] OpenCode
>
> Crear `AGENTS.md` En la raíz de tu proyecto, pega el mensaje del sistema. OpenCode lo aplica a todas las sesiones de agente del proyecto.

> [tab] OpenHands
>
> Pega el mensaje del sistema como instrucción inicial al iniciar una sesión de agente. Para proyectos persistentes, agrégalo a la configuración de tu espacio de trabajo de OpenHands.

### Paso 2: Amplíalo con tu arquitectura.

El mensaje del sistema está diseñado para ser extendido. Después de la última sección `##`, agrega el contexto específico de tu proyecto para que el agente genere código que se ajuste a tu base de código existente:

```
## Your Project Architecture

[Add your context here. Examples:]

- Stack: Node.js + TypeScript + Express, repository pattern
- Payment service lives in: src/domain/services/PaymentService.ts
- HTTP client: axios with retry via axios-retry
- Error handling: custom AppError class in src/shared/errors/
- Logging: structured JSON via pino — never log sensitive data
- All payment-related code must pass through PaymentService — no direct API calls
- PCI DSS scope: card data must NEVER appear in logs or be persisted outside Localpayment tokenization
- Environment variables follow the pattern: LOCALPAYMENT_API_KEY, LOCALPAYMENT_BASE_URL
- Tests: Jest + supertest, integration tests in __tests__/integration/
```

El agente leerá los archivos de tu proyecto y generará código que seguirá tus patrones al pie de la letra.

### Paso 3: Generación autónoma de módulos

Con el agente integrado y el contexto de tu arquitectura añadido, puedes delegar tareas de integración completas:

```
Generate the complete Localpayment PayIn integration module for our project.
Read the existing code in src/domain/services/ to understand our patterns,
then create all necessary files: API client, auth handler, webhook receiver,
and error handler. Use the Localpayment MCP to validate all endpoint schemas
before generating. Follow our repository pattern and apply all security rules.
```

El agente deberá:

1. Lee tus archivos de servicio existentes
2. Consulta el MCP de Localpayment para obtener los esquemas de endpoint actuales.
3. Genera todos los archivos en la ubicación correcta con tus convenciones de nomenclatura.
4. Aplicar automáticamente las mejores prácticas de PCI y seguridad.
5. Ejecuta tus pruebas (en herramientas como Cursor u OpenHands) y corrige cualquier fallo.

***

## Implementar mediante Framework

Las pestañas del marco que aparecen a continuación se aplican a cualquier agente de esta biblioteca. Reemplazar `SYSTEM_PROMPT` con la solicitud del sistema del agente que deseas implementar.

> [tab] MCP (cualquier herramienta)
>
> La implementación más sencilla para cualquier agente de Localpayment se realiza con cualquier herramienta compatible con MCP (Cursor, Claude Desktop, VS Code, Windsurf, ChatGPT, OpenHands, OpenCode, entre otras).
>
> 1. Configura el [servidor MCP](https://docs.localpayment.com/es/docs/mcp-server.md) para tu herramienta.
> 2. Crea una nueva sesión y pega el mensaje del sistema del agente como instrucción inicial, archivo de reglas personalizadas o instrucciones del proyecto.
>
> **En Cursor**, crea un `.cursor/rules` Archivo en tu proyecto y pega el mensaje del sistema.
>
> **En Claude Desktop**, abre la configuración de tu proyecto y pega el mensaje del sistema en el campo **Instrucciones del proyecto**.
>
> **En OpenHands**, pega el mensaje del sistema como instrucción inicial del agente antes de comenzar la tarea.

> [tab] OpenAI Agents SDK
>
> ```python theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
> import asyncio
> from agents import Agent, Runner
> from agents.mcp import MCPServerStreamableHttp
>
> SYSTEM_PROMPT = """
> [PASTE THE SYSTEM PROMPT OF YOUR CHOSEN AGENT]
> """
>
> async def main():
>     async with MCPServerStreamableHttp(
>         url="https://docs.localpayment.com/mcp"
>     ) as mcp_server:
>         agent = Agent(
>             name="localpayment-integrator",  # or localpayment-qa
>             instructions=SYSTEM_PROMPT,
>             mcp_servers=[mcp_server],
>             model="gpt-4o",
>             model_settings={"temperature": 0},
>         )
>         result = await Runner.run(
>             agent,
>             "Walk me through creating a CVU virtual account in Argentina "
>             "and handling the payment webhook."
>         )
>         print(result.final_output)
>
> asyncio.run(main())
> ```
>
> Instala el SDK:
>
> ```bash theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
> pip install openai-agents>=0.14.0
> ```

> [tab] LangChain
>
> ```python theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
> import asyncio
> from langchain_openai import ChatOpenAI
> from langchain.agents import AgentExecutor, create_openai_functions_agent
> from langchain_mcp_adapters.tools import load_mcp_tools
> from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
> from mcp import ClientSession
> from mcp.client.streamable_http import streamablehttp_client
>
> SYSTEM_PROMPT = """
> [PASTE THE SYSTEM PROMPT OF YOUR CHOSEN AGENT]
> """
>
> async def run_agent(query: str):
>     async with streamablehttp_client(
>         "https://docs.localpayment.com/mcp"
>     ) as (read, write, _):
>         async with ClientSession(read, write) as session:
>             await session.initialize()
>             tools = await load_mcp_tools(session)
>
>             llm = ChatOpenAI(model="gpt-4o", temperature=0)
>             prompt = ChatPromptTemplate.from_messages([
>                 ("system", SYSTEM_PROMPT),
>                 MessagesPlaceholder("chat_history", optional=True),
>                 ("human", "{input}"),
>                 MessagesPlaceholder("agent_scratchpad"),
>             ])
>
>             agent = create_openai_functions_agent(llm, tools, prompt)
>             executor = AgentExecutor(agent=agent, tools=tools, verbose=True)
>             return await executor.ainvoke({"input": query})
>
> result = asyncio.run(run_agent(
>     "What endpoints are available for virtual accounts in Colombia?"
> ))
> print(result["output"])
> ```
>
> Instalar dependencias:
>
> ```bash theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
> pip install langchain-mcp-adapters>=0.2.0 langchain langchain-openai mcp
> ```

> [tab] Vercel AI SDK
>
> ```typescript theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
> import { generateText } from "ai";
> import { openai } from "@ai-sdk/openai";
> import { experimental_createMCPClient as createMCPClient } from "ai";
> import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
>
> const SYSTEM_PROMPT = `
> [PASTE THE SYSTEM PROMPT OF YOUR CHOSEN AGENT]
> `;
>
> async function runAgent(userQuery: string) {
>   const mcpClient = await createMCPClient({
>     transport: new StreamableHTTPClientTransport(
>       new URL("https://docs.localpayment.com/mcp")
>     ),
>   });
>
>   const tools = await mcpClient.tools();
>
>   const { text } = await generateText({
>     model: openai("gpt-4o"),
>     system: SYSTEM_PROMPT,
>     prompt: userQuery,
>     tools,
>     maxSteps: 10,
>     temperature: 0,
>   });
>
>   await mcpClient.close();
>   return text;
> }
>
> const result = await runAgent(
>   "Generate a complete PayIn integration for SPEI virtual accounts in Mexico."
> );
> console.log(result);
> ```
>
> Instalar dependencias:
>
> ```bash theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
> npm install ai @ai-sdk/openai @modelcontextprotocol/sdk
> ```

> [tab] CrewAI
>
> ```python theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
> import asyncio
> from crewai import Agent, Task, Crew
> from crewai_tools import MCPServerAdapter
>
> SYSTEM_PROMPT = """
> [PASTE THE SYSTEM PROMPT OF YOUR CHOSEN AGENT]
> """
>
> async def run_crew():
>     async with MCPServerAdapter(
>         server_params={
>             "url": "https://docs.localpayment.com/mcp",
>             "transport": "streamable_http"
>         }
>     ) as adapter:
>         integrator_agent = Agent(
>             role="Localpayment Integration Specialist",
>             goal="Help developers build accurate Localpayment API integrations",
>             backstory=SYSTEM_PROMPT,
>             tools=adapter.tools,
>             verbose=True,
>             allow_delegation=False,
>             llm_config={"temperature": 0},
>         )
>
>         task = Task(
>             description=(
>                 "Build a complete integration guide for creating CVU virtual "
>                 "accounts in Argentina. Query the live MCP spec for all details."
>             ),
>             expected_output=(
>                 "Step-by-step guide with working code, expected API responses, "
>                 "and reconciliation field mapping — verified against the live spec."
>             ),
>             agent=integrator_agent,
>         )
>
>         crew = Crew(agents=[integrator_agent], tasks=[task], verbose=True)
>         return crew.kickoff()
>
> result = asyncio.run(run_crew())
> print(result)
> ```
>
> Instalar dependencias:
>
> ```bash theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
> pip install "crewai-tools[mcp]"
> ```

> [tab] AgentScope
>
> ```python theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
> import asyncio
> import agentscope
> from agentscope.agents import ReActAgent
> from agentscope.mcp import HttpStatelessClient
> from agentscope.tool import Toolkit
>
> SYSTEM_PROMPT = """
> [PASTE THE SYSTEM PROMPT OF YOUR CHOSEN AGENT]
> """
>
> async def run_agent(query: str):
>     agentscope.init(
>         model_configs=[{
>             "model_type": "openai_chat",
>             "config_name": "gpt-4o",
>             "model_name": "gpt-4o",
>             "api_key": "YOUR_OPENAI_API_KEY",
>             "generate_args": {"temperature": 0},
>         }]
>     )
>
>     mcp_client = HttpStatelessClient(
>         name="localpayment",
>         transport="streamable_http",
>         url="https://docs.localpayment.com/mcp",
>     )
>
>     toolkit = Toolkit()
>     await toolkit.add_mcp_client(mcp_client)
>
>     agent = ReActAgent(
>         name="localpayment-integrator",
>         model_config_name="gpt-4o",
>         sys_prompt=SYSTEM_PROMPT,
>         tools=toolkit.get_tools(),
>     )
>
>     response = agent({"content": query})
>     return response.content
>
> result = asyncio.run(run_agent(
>     "What virtual account creation endpoints exist and what fields are "
>     "required for Argentina?"
> ))
> print(result)
> ```
>
> Instalar dependencias:
>
> ```bash theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
> pip install "agentscope[full]>=1.0.18"
> ```
>
> Requiere Python 3.10 o superior.

> [tab] Amazon Bedrock
>
> Amazon Bedrock admite MCP de forma nativa a través de **Bedrock Agents** (recomendado para entornos de producción) o directamente a través de la **API de Converse** con definiciones de herramientas integradas.
>
> **Opción 1: API Converse (la más sencilla, sin necesidad de Lambda):**
>
> ```python theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
> import json
> import boto3
>
> SYSTEM_PROMPT = """
> [PASTE THE SYSTEM PROMPT OF YOUR CHOSEN AGENT]
> """
>
> bedrock_runtime = boto3.client(
>     service_name="bedrock-runtime",
>     region_name="us-east-1"
> )
>
> response = bedrock_runtime.converse(
>     modelId="anthropic.claude-sonnet-4-6",
>     system=[{"text": SYSTEM_PROMPT}],
>     inferenceConfig={"temperature": 0, "maxTokens": 8192},
>     messages=[{
>         "role": "user",
>         "content": [{
>             "text": (
>                 "What are the required fields to create a virtual account "
>                 "in Peru? Verify by reading the live API spec."
>             )
>         }]
>     }]
> )
>
> print(response["output"]["message"]["content"][0]["text"])
> ```
>
> **Opción 2: Bedrock Agents con MCP (producción):**
>
> Para una integración completa de herramientas MCP en producción, configura el servidor MCP de Localpayment como un grupo de acciones en Amazon Bedrock Agents. Consulta la [documentación de AWS Bedrock Agents](https://docs.aws.amazon.com/bedrock/latest/userguide/agents.html) para ver los detalles de configuración.
>
> Instalar dependencias:
>
> ```bash theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
> pip install boto3
> ```

> [tab] OpenCode
>
> [OpenCode](https://opencode.ai) es un agente de IA de terminal de código abierto con compatibilidad nativa con MCP.
>
> Agrega lo siguiente a tu `opencode.jsonc` archivo de configuración:
>
> ```json theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
> {
>   "$schema": "https://opencode.ai/config.json",
>   "mcp": {
>     "localpayment": {
>       "type": "remote",
>       "url": "https://docs.localpayment.com/mcp",
>       "enabled": true
>     }
>   }
> }
> ```
>
> Luego crea un `AGENTS.md` Archivo en tu proyecto con el indicador del sistema:
>
> ```markdown theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
> [PASTE THE SYSTEM PROMPT OF YOUR CHOSEN AGENT]
> ```
>
> OpenCode aplicará las instrucciones del agente y llamará automáticamente a las herramientas MCP de Localpayment cuando sea pertinente.

> [tab] OpenHands
>
> [OpenHands](https://github.com/All-Hands-AI/OpenHands) es una plataforma de desarrollo de software con IA de código abierto con compatibilidad nativa con MCP.
>
> **Desde la interfaz de OpenHands:**
>
> 1. Ve a **Settings → MCP** y agrega:
>    * **Transporte**: Streamable HTTP
>    * **URL**: `https://docs.localpayment.com/mcp`
> 2. Inicia una nueva tarea y pega el mensaje del sistema del agente como instrucción inicial.
>
> **A través de `config.toml`:**
>
> ```toml theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
> [mcp]
> [[mcp.servers]]
> name = "localpayment"
> transport = "streamable_http"
> url = "https://docs.localpayment.com/mcp"
> ```

***

## Comparación de marcos

| Framework | Lenguaje | Tipo | MCP nativo | Licencia | Lo mejor para |
| :- | :- | :- | :-: | :- | :- |
| **MCP (cualquier herramienta)** | Cualquier | Herramienta/IDE | ✔ | Varía | desarrollo integrado en IDE |
| **OpenAI Agents SDK** | Python | Framework | ✔ | MIT | agentes autónomos simples |
| **LangChain** | Python / TS | Framework | ✔ | MIT | Cadenas y pipelines complejos |
| **Vercel AI SDK** | TypeScript | Framework | ✔ | Apache 2.0 | Aplicaciones web y Next.js |
| **CrewAI** | Python | Framework | ✔ | MIT | Flujos de trabajo multiagente |
| **AgentScope** | Python | Framework | ✔ | Apache 2.0 | Sistemas multiagente de producción |
| **Amazon Bedrock** | Python | Servicio en la nube | ✔ (nativo) | Comercial | Implementaciones empresariales nativas de AWS |
| **OpenCode** | Cualquier | Agente terminal | ✔ | MIT | Agente de codificación de IA de terminal de código abierto |
| **OpenHands** | Cualquier | Plataforma | ✔ | MIT | Plataforma de agente de codificación de código abierto |

***

## Estándares y ecosistema

Los agentes de Localpayment se basan en estándares abiertos. Comprender el ecosistema resulta útil al ampliar la funcionalidad de los agentes o al crear flujos de trabajo multiagente.

| Estándar | Qué es | Pertinencia |
| :- | :- | :- |
| **[MCP](https://modelcontextprotocol.io)** | Protocolo de contexto de modelo: estándar abierto para la conectividad de herramientas de IA. | Base de todos los agentes de Localpayment |
| **[Protocolo A2A](https://github.com/a2aproject/A2A)** | Agent2Agent: protocolo abierto de Google/Linux Foundation para la comunicación entre agentes mediante JSON-RPC. | Permite flujos de trabajo multiagente entre los agentes de Localpayment y tus agentes internos. |
| **[AGENTS.md](https://agents.md)** | Formato abierto para empaquetar instrucciones de agentes (utilizado en más de 60.000 proyectos, Claude Code, Goose y otros). | Archivo estándar para distribuir las indicaciones del sistema del agente de Localpayment dentro de tu proyecto. |
| **[Open Agent Format (OAF)](https://openagentformat.com)** | Formato de distribución basado en ZIP para agentes portátiles en múltiples plataformas de IA. | Empaqueta y comparte los agentes de Localpayment con todo tu equipo. |

***

## Flujos de trabajo multiagente

Los agentes de Localpayment trabajan junto con los agentes de tu proyecto existente. Un flujo de trabajo típico combina tus agentes internos (que conocen tu código fuente y arquitectura) con los agentes especializados de Localpayment (que conocen la API de Localpayment a través de MCP):

```mermaid theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
%%{init: {'theme': 'base', 'themeVariables': {'fontSize': '14px', 'fontFamily': 'sans-serif'}}}%%
sequenceDiagram
    autonumber
    participant Dev as Desarrollador
    participant Orch as Agente interno
    participant Int as Agente integrador
    participant QA as Agente de QA
    participant MCP as Servidor MCP

    Dev->>Orch: Construir el módulo de PayIn para Colombia

    rect rgb(219, 234, 254)
        Note over Orch,MCP: Fase de integración
        activate Int
        Orch->>Int: Generar el módulo de PayIn (Colombia, Bre-B)
        Int->>MCP: list-endpoints / get-endpoint / search+fetch
        MCP-->>Int: Esquemas y documentación en vivo
        Int-->>Orch: Módulo generado (autenticación + cliente de API + manejador de webhooks)
        deactivate Int
    end

    rect rgb(220, 252, 231)
        Note over Orch,MCP: Fase de validación
        activate QA
        Orch->>QA: Validar esta integración
        QA->>MCP: get-endpoint / search de códigos de error + guías de seguridad
        MCP-->>QA: Esquemas y documentación en vivo
        QA-->>Orch: PASS: autenticación, campos, HTTPS / WARN: reintentos / FAIL: idempotencia
        deactivate QA
    end

    rect rgb(254, 243, 199)
        Note over Orch,Int: Ciclo de corrección
        Orch->>Int: Corregir los elementos FAIL
        Int-->>Orch: Módulo actualizado
        Orch->>QA: Volver a validar
        QA-->>Orch: Todas las verificaciones aprobadas
    end

    Orch-->>Dev: Módulo de integración completo y validado
```

**Ejemplo de mensaje para tu agente orquestador (Cursor / Claude Code):**

```
You are working on our Express.js payment service. Use the Localpayment 
Integrator Agent context (already in .cursor/rules) to:

1. Generate the complete Localpayment PayIn module for Colombia (Bre-B) 
   in src/services/payments/localpayment/, following our existing service 
   pattern from src/services/payments/stripe/

2. Once generated, apply the Localpayment QA Agent checklist to validate 
   the implementation. Report any FAIL or WARN items.

3. Fix any FAIL items found in the QA review.

Use the Localpayment MCP for all API spec details.
```

***

## Comparte y distribuye a tus agentes

A diferencia de los servidores MCP (que tienen enlaces de instalación directa), las indicaciones del sistema del agente se distribuyen como archivos. El enfoque recomendado depende de la configuración de tu equipo:

**Para uso individual:**

Copia el mensaje del sistema de esta página y agrégalo al archivo de reglas o instrucciones de tu herramienta. No requiere instalación.

**Para la distribución en equipo a través de git:**

La forma más fiable de compartir agentes con tu equipo es subir los archivos de configuración del sistema al repositorio de tu proyecto. Todos los miembros del equipo obtienen automáticamente la misma configuración de agente al clonar o actualizar el repositorio.

Para Claude Code — crear `.claude/agents/localpayment-integrator.md`:

```markdown theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
---
name: localpayment-integrator
description: Specialist agent for building Localpayment API integrations. Use for any Localpayment payment, virtual account, webhook, or error code question.
---

[PASTE THE LOCALPAYMENT INTEGRATOR AGENT SYSTEM PROMPT HERE]
```

Para Cursor — commit `.cursor/rules` con el contenido de solicitud del sistema. Cada miembro del equipo que trabaja en ese repositorio obtiene el agente automáticamente.

Para OpenCode — commit `AGENTS.md` con la solicitud del sistema. OpenCode lo carga en cada sesión.

**Siguiendo el estándar abierto AGENTS.md:**

El [formato AGENTS.md](https://agents.md) es reconocido por Claude Code, Goose y otras plataformas de agentes. Utiliza metadatos en formato YAML y instrucciones en formato Markdown, la misma estructura que las indicaciones del sistema mencionadas anteriormente.

***

## Sesión de ejemplo

**Desarrollador:** Necesito validar mi integración de CVU de Argentina antes de ponerla en marcha.

**Agente de control de calidad de Localpayment:** *(llama a `get-endpoint POST /api/virtual-account` → lee el esquema en vivo)*
*(llama a `search("receive payment notifications")` → obtiene la guía de webhooks)*

**Componente revisado**: `POST /api/virtual-account` (CVU de Argentina)
**Versión de la especificación consultada**: Esquema en vivo mediante `get-endpoint` de MCP

✅ APROBADO

* `externalId` es formato UUID
* Todos los campos obligatorios están presentes: `country`, `accountNumber`, `beneficiary.type`, `beneficiary.name`

⚠️ ADVERTENCIA

* `beneficiary.document` Es opcional para las empresas locales argentinas, pero se recomienda para la conciliación.

❌ FALLO

* El controlador de webhook no comprueba `internalId` Para el procesamiento de duplicados, agrega una verificación de idempotencia antes de acreditar el pago.

**Resumen**: La integración está completa en un 85%. Corrige la comprobación de idempotencia antes de implementarla en producción.

***

> [card] [Biblioteca de indicaciones](https://docs.localpayment.com/es/docs/prompt-library.md)
>
> Indicaciones listas para usar para sacar el máximo partido a cualquier agente de Localpayment.

> [card] [Seguridad de IA](https://docs.localpayment.com/es/docs/ai-security.md)
>
> Buenas prácticas para el uso seguro de herramientas de IA en un contexto de integración fintech.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.