Skip to main content

Agent toolkit quickstart guide

PayPal's agent toolkit supports the integration of PayPal APIs into AI agent workflows using OpenAI's Agents SDK , Vercel's AI SDK , Model Context Protocol (MCP) , LangChain , and CrewAI. This guide provides a step-by-step process for setting up the server, building a basic conversational front-end interface using Next.js, and testing the integration. It also includes best practices to follow for secure and efficient usage.

Key features

The agent toolkit from PayPal enables you to:

  • Integrate with PayPal APIs to access orders, invoices, subscriptions, shipment tracking, transaction details, and dispute management through pre-built functions.
  • Develop with your preferred tools, including:
  • Build custom agent capabilities to extend core PayPal features and connect with other toolkits to create multi-step agent workflows.

1. Set up your environment

To prepare for an integration, set up your environment first.

Python

  1. Install Python 3.11 or later and pip (Python package manager).
  2. Run pip install paypal-agent-toolkit to install the PayPal agent toolkit.

TypeScript

  1. Download and install Node.js version 18 or later from the official Node.js website.
  2. Run the command npm install @paypal/agent-toolkit to install the agent toolkit, or download the package from the GitHub repo.
  3. Get your PayPal account's client ID and secret from PayPal Developer Dashboard. You'll need them to configure this library.

Integration

PayPal's agent toolkit supports OpenAI’s Agents SDK, Vercel’s AI SDK, and Model Context Protocol (MCP). It works with LLM providers that support function calling and is compatible with TypeScript and Python.

For integration steps, see the corresponding topic for your AI platform in this guide.

For information about setting up the front end for testing any of these integrations, see the agent toolkit quickstart guide.

Open AI Agents SDK

Complete the following steps to integrate PayPal's agent toolkit with OpenAI's Agents SDK. The agent toolkit works with Agents SDK, which passes it as a list of tools.

  1. Import PayPal’s agent toolkit into your code.
  2. Update your clientId and clientSecret with the values from PayPal Developer Dashboard.
from paypal_agent_toolkit.openai.toolkit import PayPalToolkit 
from paypal_agent_toolkit.common.configuration import Configuration, Context

configuration = Configuration(
actions={
"orders": {
"create": True,
"get": True,
"capture": True,
}
},
context=Context(
sandbox=True
)
)

# Initialize toolkit
toolkit = PayPalToolkit(client_id=PAYPAL_CLIENT_ID, secret=PAYPAL_SECRET, configuration = configuration)
  1. You can use the agent toolkit's functions and other tools as your integration requires.
from agents import Agent  

tools = toolkit.get_tools()

agent = Agent(
name="PayPal Assistant",
instructions="""
You're a helpful assistant specialized in managing PayPal transactions:
- To create orders, invoke create_order.
- After approval by user, invoke capture_order.
- To check an order status, invoke get_order_status.
""",
tools=tools
)
  1. Test the integration.

Vercel AI SDK

Complete the following steps to integrate PayPal's agent toolkit with Vercel's AI SDK. The agent toolkit works with Vercel's AI SDK, which passes it as a list of tools.  

  1. Import PayPal's agent toolkit into your code.

  2. Update your clientId and clientSecret with the values from PayPal Developer Dashboard.

import { PayPalAgentToolkit } from '@paypal/agent-toolkit/ai-sdk';
const paypalToolkit = new PayPalAgentToolkit({
clientId: process.env.PAYPAL_CLIENT_ID,
clientSecret: process.env.PAYPAL_CLIENT_SECRET,
configuration: {
actions: {
invoices: {
create: true,
list: true,
send: true,
sendReminder: true,
cancel: true,
generateQRC: true,
},
products: { create: true, list: true, update: true },
subscriptionPlans: { create: true, list: true, show: true },
shipment: { create: true, show: true, cancel: true },
orders: { create: true, get: true },
disputes: { list: true, get: true },
},
},
});
  1. Use PayPal's agent toolkit's functions and other tools as your integration requires. 
const llm: LanguageModelV1 = getModel(); // The model to be used with ai-sdk
const { text: response } = await generateText({
model: llm,
tools: {
...paypalToolkit.getTools(),
// Extend with other tools
},
maxSteps: 10,
prompt: `Create an order for $50 for custom handcrafted item and get the payment link.`,
});
  1. Test your integration.

Model Context Protocol

Model Context Protocol (MCP) supports managing and passing relevant information to models with appropriate context, so they operate properly within a given scope. Using this technology, PayPal developed an MCP server to enable merchants to use natural language with their favorite MCP client.

To install the MCP server in a local configuration: 

  1. Update the configuration file in your favorite MCP client:   

    1. Open the MCP client. 
    2. In the configuration settings for the client, locate the external tools or connectors configuration section, and add the PayPal connector configuration that follows this procedure. In Claude, for example, you add this to ~/Claude/claude_desktop_config.json.
    3. In the new entry, replace YOUR_PAYPAL_ACCESS_TOKEN with your actual PayPal access token. Alternatively, you can set the PAYPAL_ACCESS_TOKEN as an environment variable. You also can pass it as an argument using --access-token in args.

    Set the PAYPAL_ENVIRONMENT to SANDBOX for testing or PRODUCTION for your production environment.

  2. Test your integration:

    1. Quit and restart the MCP client to apply your changes.
    2. Ask the MCP client to perform one of the supported tasks. For example, ask the MCP client to list your PayPal invoices for the last month.
{
"mcpServers": {
"paypal": {
"command": "npx",
"args": [
"-y",
"@paypal/mcp",
"--tools=all"
],
"env": {
"PAYPAL_ACCESS_TOKEN": "YOUR_PAYPAL_ACCESS_TOKEN",
"PAYPAL_ENVIRONMENT": "SANDBOX"
}
}
}
}

If your test doesn't produce the results you expect, try the ideas here.

LangChain

Complete the following steps to integrate the agent toolkit from PayPal with LangChain. The agent toolkit works with LangChain, which passes it as a list of tools.

  1. Import PayPal Agent toolkit into your code.
  2. Update your clientId and clientSecret with the values from PayPal Developer Dashboard.
from langchain.agents import initialize_agent, AgentType
from langchain_openai import ChatOpenAI
from paypal_agent_toolkit.langchain.toolkit import PayPalToolkit

# Initialize Langchain Toolkit
toolkit = PayPalToolkit(client_id=PAYPAL_CLIENT_ID, secret=PAYPAL_SECRET, configuration = configuration)
tools = toolkit.get_tools()

# Setup LangChain Agent
agent = initialize_agent(
tools=tools,
llm=llm,
agent=AgentType.OPENAI_FUNCTIONS,
verbose=True
)

prompt = "Create a PayPal order for $50 for Premium News service."
# Run the agent with the defined prompt
result = agent.run(prompt)
  1. Test the integration.

CrewAI

Complete the following steps to integrate the agent toolkit from PayPal with CrewAI. The agent toolkit works with CrewAI, which passes it as a list of tools.

  1. Import PayPal Agent toolkit into your code.
  2. Update your clientId and clientSecret with the values from PayPal Developer Dashboard.
from crewai import Agent, Crew, Task
from paypal_agent_toolkit.crewai.toolkit import PayPalToolkit

# Setup PayPal CrewAI Toolkit
toolkit = PayPalToolkit(client_id=PAYPAL_CLIENT_ID, secret=PAYPAL_SECRET, configuration = configuration)
tools = toolkit.get_tools()

# Define an agent specialized in PayPal transactions
agent = Agent(
role="PayPal Assistant",
goal="Help users create and manage PayPal transactions",
backstory="You are a finance assistant skilled in PayPal operations.",
tools=toolkit.get_tools(),
allow_delegation=False
)

# Define a CrewAI Task to create a PayPal order
task = Task(
description="Create a PayPal order for $50 for Premium News service.",
expected_output="A PayPal order ID",
agent=agent
)

# Assemble Crew with defined agent and task
crew = Crew(agents=[agent], tasks=[task], verbose=True,
planning=True,)
  1. Test the integration.

Note: For a complete list of the tools that PayPal's agent toolkit includes, see the list of available tools.

2. Build the front end

Using the Next.js framework, complete the following tasks.

Create a Next.js project

If you don't have a Next.js app already, create one.

npx create-next-app@latest paypal-integration --typescript
cd paypal-integration
npm install

Create a chat interface

Modify app/page.tsx to create a chat interface for interacting with the PayPal agent.

import React, { useState } from 'react';

const Home: React.FC = () => {
const [message, setMessage] = useState('');
const [chat, setChat] = useState<{ sender: 'user' | 'agent'; text: string }[]>([]);
const handleSendMessage = async () => {
setChat((prevChat) => [...prevChat, { sender: 'user', text: message }]);
const response = await fetch('/api/chat', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ message }),
});
const data = await response.json();
setChat((prevChat) => [...prevChat, { sender: 'agent', text: data.response }]);
setMessage('');
};

return (
<div>
<h1>PayPal Chat Interface</h1>
<div>
{chat.map((c, index) => (
<div key={index} className={c.sender}>
{c.sender}: {c.text}
</div>
))}
</div>
<input
type="text"
value={message}
onChange={(e) => setMessage(e.target.value)}
/>
<button onClick={handleSendMessage}>Send</button>
</div>
);
};

export default Home;

3. Test the integration

After you finish the integration, test it by setting up an API route.

Execute this code in app/api/chat/route.ts.

import { NextRequest, NextResponse } from 'next/server';
import { openai } from '@ai-sdk/openai';
import { generateText } from 'ai';
import { PayPalAgentToolkit } from '@paypal/agent-toolkit/ai-sdk';

const paypalToolkit = new PayPalAgentToolkit({
clientId: process.env.PAYPAL_CLIENT_ID,
clientSecret: process.env.PAYPAL_CLIENT_SECRET,
configuration: {
actions: {
orders: { create: true, get: true },
invoices: { create: true, list: true },
// Extend with other actions as needed
},
},
});

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

// Define System Prompt for controlling behavior
const systemPrompt = 'This is a PayPal agent. You are tasked with handling PayPal orders and providing relevant information.';

const { text: response } = await generateText({
model: openai('gpt-4o'),
tools: paypalToolkit.getTools(),
maxSteps: 10,
prompt: message,
system: systemPrompt,
});

return NextResponse.json({ response });
} catch (error) {
const errorMessage = error instanceof Error
? error.message
: 'An unknown error occurred';

return NextResponse.json(
{ error: errorMessage },
{ status: 500 }
);
}
}

4. Start the application

To start the application, execute npm run dev, and visit http://localhost:3000.

Get OpenAI API keys

Complete the following steps to generate and store your OpenAI keys to use in your integration with PayPal's agent toolkit.

  1. Create an OpenAI account, and complete all registration steps.
  2. Generate your API keys:
  3. Log into OpenAI, and navigate to the API Keys section of your account.
  4. Select Create a new secret key.
  5. Save the generated key securely. You use this key in your env.local file for your agent toolkit integration.

Best practices

To have the best integration experience, follow these tips:

  • Sandbox environment: Always use the sandbox environment for initial testing to avoid real transactions.
  • API keys: Keep client ID, client secret, and API keys secure. Do not hard-code them in your source files.
  • Environment variables: Use environment variables to manage sensitive data.
  • Error handling: Implement robust error handling to ensure reliable integration.
  • System prompts: Use well-defined system prompts to control the behavior of the agent effectively.

Additional resources

For more information about the concepts covered here, see these additional documents: