Saltar al contenido
SDK Quickstarts

Conecta tu agente de IA a Trusteed

Ejemplos listos para copiar con los 3 SDKs de IA más usados. Cada ejemplo incluye verificación de trust score.

OpenAI Agents SDK

OpenAI Agents SDK — Python

Instalarpip install openai-agents
Versión probada: openai-agents ≥ 0.14.0
PythonAgente de compras con verificación de confianza
import asyncio
from agents import Agent, Runner
from agents.mcp import MCPServerStreamableHttp

async def main():
    async with MCPServerStreamableHttp(
        name="trusteed",
        params={
            "url": "https://trusteed.xyz/demo-store/mcp",
            "headers": {"X-Agent-Api-Key": "agnt_your_key"},
            "timeout": 30,
        },
        cache_tools_list=True,
    ) as mcp:
        agent = Agent(
            name="shopping-agent",
            instructions="""
            You are a shopping assistant for Trusteed.
            IMPORTANT: Before any checkout, always call get_merchant_profile
            and verify the merchant's trust level. If it is below your acceptable
            threshold, stop and inform the user.
            Methodology: GET /api/v1/trust/methodology
            """,
        )

        result = await Runner.run_async(
            agent,
            "Search for laptops under $1500, verify merchant trust, and create a cart."
        )
        print(result.final_output)

asyncio.run(main())

El agente recibe trust_score en la respuesta de get_merchant_profile. Con las instrucciones del system prompt, el modelo verifica automáticamente el umbral antes de llamar a create_cart.

Claude Agent SDK

Claude Agent SDK — TypeScript

Instalarnpm install @anthropic-ai/claude-agent-sdk
Versión probada: @anthropic-ai/claude-agent-sdk ≥ 0.2.0
Nota: El SDK está en desarrollo activo — revisa el CHANGELOG antes de actualizar a minor versions.
TypeScriptAgente con allowedTools y trust check
import { query } from "@anthropic-ai/claude-agent-sdk";

// Source: https://code.claude.com/docs/en/agent-sdk/mcp#httpsse-servers

async function main() {
  for await (const message of query({
    prompt: `
      1. Call search_products with query "laptop" limit 5
      2. Call get_merchant_profile to get the merchant's trust level
      3. If the trust level is above your acceptable threshold, call create_cart with the first result
      4. Report the cart_id and trust level
    `,
    options: {
      mcpServers: {
        trusteed: {
          type: "http",
          url: "https://trusteed.xyz/demo-store/mcp",
          headers: {
            "X-Agent-Api-Key": process.env.TRUSTEED_API_KEY ?? "",
          },
        },
      },
      allowedTools: [
        "mcp__trusteed__search_products",
        "mcp__trusteed__get_merchant_profile",
        "mcp__trusteed__create_cart",
      ],
    },
  })) {
    if (message.type === "result" && message.subtype === "success") {
      process.stdout.write(JSON.stringify(message.result) + "\n");
    }
    if (message.type === "assistant") {
      for (const block of message.message.content) {
        if (block.type === "text") {
          process.stdout.write(block.text);
        }
      }
    }
  }
}

main().catch((err) => process.stderr.write(String(err)));

allowedTools limita qué herramientas MCP puede usar el agente — importante para reducir blast radius en producción.

Vercel AI SDK

Vercel AI SDK — TypeScript

Instalarnpm install ai @ai-sdk/openai
Versión probada: ai ≥ 6.0.0
Nota: experimental_createMCPClient aún está en beta — la API puede cambiar.
TypeScript (Node.js)generateText con cliente MCP
import { experimental_createMCPClient as createMCPClient } from "ai";
import { generateText } from "ai";
import { openai } from "@ai-sdk/openai";

async function main() {
  const mcpClient = await createMCPClient({
    transport: {
      type: "http",
      url: "https://trusteed.xyz/demo-store/mcp",
      headers: {
        "X-Agent-Api-Key": process.env.TRUSTEED_API_KEY ?? "",
      },
    },
  });

  const tools = await mcpClient.tools();

  const { text, toolCalls } = await generateText({
    model: openai("gpt-4o"),
    tools,
    maxSteps: 6,
    system: `You are a shopping assistant.
IMPORTANT: Always call get_merchant_profile first and verify the merchant's trust level.
If the merchant's trust level is below your acceptable threshold, do NOT create a cart. Inform the user instead.`,
    prompt: "Find me a laptop under $1500 and start the checkout process.",
  });

  process.stdout.write("Response: " + text + "\n");
  process.stdout.write("Tool calls: " + toolCalls.length + "\n");

  await mcpClient.close();
}

main().catch((err) => process.stderr.write(String(err)));
TypeScript (Next.js App Router)Streaming en Next.js App Router
// app/api/shop/route.ts
import { experimental_createMCPClient as createMCPClient } from "ai";
import { streamText } from "ai";
import { openai } from "@ai-sdk/openai";

export async function POST(req: Request) {
  const { message } = await req.json();

  const mcpClient = await createMCPClient({
    transport: {
      type: "http",
      url: `https://trusteed.xyz/${process.env.STORE_SLUG}/mcp`,
      headers: { "X-Agent-Api-Key": process.env.TRUSTEED_API_KEY ?? "" },
    },
  });

  const tools = await mcpClient.tools();

  const result = streamText({
    model: openai("gpt-4o"),
    tools,
    maxSteps: 8,
    system: "Shopping assistant. Verify the merchant's trust level is above your acceptable threshold before checkout.",
    messages: [{ role: "user", content: message }],
    onFinish: () => mcpClient.close(),
  });

  return result.toDataStreamResponse();
}

streamText con onFinish cierra el cliente MCP automáticamente cuando la respuesta finaliza, evitando fugas de conexión.

Patrón de Trust Check — común a los 3 SDKs

Niveles de confianza que tu agente debe aplicar antes de iniciar checkout

PuntuaciónNivelAcción del agente
MáximaELITEProceder sin fricción
AltaVERIFIEDProceder con confirmación estándar
ElegibleSTANDARDMínimo elegible para checkout
Bajo umbralNO PROCEDERNo iniciar checkout

Metodología completa: GET /api/v1/trust/methodology

¿Listo para conectar? Obtén tu API key en segundos.

Obtener API Key
SDK Quickstarts — Agentes IA | Trusteed