### Run the Server Source: https://github.com/mondaycom/agent-tool-protocol/blob/master/examples/oauth-example/README.md Start the development server. This example uses in-memory storage and does not require a database for initial setup. Data will be lost on restart. ```bash npm run dev ``` -------------------------------- ### Start the Example Source: https://github.com/mondaycom/agent-tool-protocol/blob/master/examples/checkpoint-recovery/README.md Execute this command to start the LangChain agent example. ```bash yarn start ``` -------------------------------- ### Run Quickstart Example Source: https://github.com/mondaycom/agent-tool-protocol/blob/master/README.md Navigate to the quickstart example directory and run the script using npm. Ensure NODE_OPTIONS is set for Node.js 20+. ```bash cd examples/quickstart NODE_OPTIONS='--no-node-snapshot' npm start ``` -------------------------------- ### Install and Run Token Refresh Example Source: https://github.com/mondaycom/agent-tool-protocol/blob/master/examples/token-refresh/README.md Install dependencies using yarn and run the example server with tsx. ```bash yarn install tsx server.ts ``` -------------------------------- ### Full Quickstart: OpenAPI, MCP, and LangChain Integration Source: https://context7.com/mondaycom/agent-tool-protocol/llms.txt A comprehensive example demonstrating server setup, direct client usage, and LangChain agent integration. It loads an OpenAPI spec, connects to an MCP server, and uses an LLM to interact with the available tools. ```typescript import { createServer, loadOpenAPI } from '@mondaydotcomorg/atp-server'; import { AgentToolProtocolClient } from '@mondaydotcomorg/atp-client'; import { MCPConnector } from '@mondaydotcomorg/atp-mcp-adapter'; import { createATPTools } from '@mondaydotcomorg/atp-langchain'; import { ChatOpenAI } from '@langchain/openai'; import { createReactAgent } from '@langchain/langgraph/prebuilt'; process.env.ATP_JWT_SECRET = process.env.ATP_JWT_SECRET ?? 'dev-secret'; async function main() { // 1. Server const server = createServer({ execution: { timeout: 30_000 } }); const petstore = await loadOpenAPI('https://petstore.swagger.io/v2/swagger.json', { name: 'petstore', filter: { methods: ['GET'] }, }); const connector = new MCPConnector(); const playwright = await connector.connectToMCPServer({ name: 'playwright', transport: 'stdio', command: 'npx', args: ['@playwright/mcp@latest'], }); server.use([petstore, playwright]); await server.listen(3333); // 2. Direct client usage const client = new AgentToolProtocolClient({ baseUrl: 'http://localhost:3333' }); await client.init({ name: 'demo' }); const directResult = await client.execute(` const pets = await api.petstore.findPetsByStatus({ status: 'available' }); return { total: pets.length, categories: [...new Set(pets.map((p: any) => p.category?.name).filter(Boolean))].slice(0, 5), sample: pets.slice(0, 3).map((p: any) => ({ name: p.name, status: p.status })), }; `); console.log('Direct result:', JSON.stringify(directResult.result, null, 2)); // 3. LangChain agent usage const llm = new ChatOpenAI({ modelName: 'gpt-4o-mini', temperature: 0 }); const { tools } = await createATPTools({ serverUrl: 'http://localhost:3333', llm }); const agent = createReactAgent({ llm, tools }); const agentResult = await agent.invoke({ messages: [{ role: 'user', content: 'How many pets are available in the petstore? Summarise by category.', }], }); console.log('Agent answer:', agentResult.messages.at(-1)!.content); await server.stop(); await connector.disconnectAll(); } main().catch(console.error); ``` -------------------------------- ### Publish with Custom Tag Example Source: https://github.com/mondaycom/agent-tool-protocol/blob/master/docs/publishing.md Example of publishing a prerelease with a custom tag and how users can install it. ```bash # Use a custom identifier like "test" or "feature-xyz" # This creates versions like: 0.18.4-test.0 # Users install with: npm install @mondaydotcomorg/atp-server@test ``` -------------------------------- ### Run LangChain Agent Example Source: https://github.com/mondaycom/agent-tool-protocol/blob/master/README.md Navigate to the LangChain quickstart example directory and run the script using npm. Ensure your OpenAI API key is set and NODE_OPTIONS is configured. ```bash cd examples/langchain-quickstart export OPENAI_API_KEY=sk-... NODE_OPTIONS='--no-node-snapshot' npm start ``` -------------------------------- ### Publish RC from Feature Branch Example Source: https://github.com/mondaycom/agent-tool-protocol/blob/master/docs/publishing.md Example of pushing a feature branch and installing the corresponding RC package. ```bash # 1. Push your branch git push origin gadsh/plugin-compiler # 2. Go to Actions → Publish Prerelease → Run workflow # - Branch: gadsh/plugin-compiler # - Prerelease identifier: rc # - Leave other options default # 3. Users install with: npm install @mondaydotcomorg/atp-compiler@rc ``` -------------------------------- ### Start ATP Server Source: https://github.com/mondaycom/agent-tool-protocol/blob/master/examples/quickstart/README.md Run this command in your terminal to start the Agent Tool Protocol server and execute the example. ```bash npm start ``` -------------------------------- ### Quickstart ATP Server and Client Example Source: https://github.com/mondaycom/agent-tool-protocol/blob/master/README.md Integrates OpenAPI (Petstore) and MCP (Playwright) with ATP. Sets up a server, loads an OpenAPI spec, connects to an MCP server, and executes filtered API data. ```typescript import { createServer, loadOpenAPI } from '@mondaydotcomorg/atp-server'; import { AgentToolProtocolClient } from '@mondaydotcomorg/atp-client'; import { MCPConnector } from '@mondaydotcomorg/atp-mcp-adapter'; process.env.ATP_JWT_SECRET = process.env.ATP_JWT_SECRET || 'test-secret-key'; async function main() { const server = createServer({}); // Load OpenAPI spec (supports OpenAPI 3.0+ and Swagger 2.0) const petstore = await loadOpenAPI('https://petstore.swagger.io/v2/swagger.json', { name: 'petstore', filter: { methods: ['GET'] }, }); // Connect to MCP server const mcpConnector = new MCPConnector(); const playwright = await mcpConnector.connectToMCPServer({ name: 'playwright', command: 'npx', args: ['@playwright/mcp@latest'], }); server.use([petstore, playwright]); await server.listen(3333); // Create client and execute code const client = new AgentToolProtocolClient({ baseUrl: 'http://localhost:3333', }); await client.init({ name: 'quickstart', version: '1.0.0' }); // Execute code that filters, maps, and transforms API data const result = await client.execute(` const pets = await api.petstore.findPetsByStatus({ status: 'available' }); const categories = pets .filter(p => p.category?.name) .map(p => p.category.name) .filter((v, i, a) => a.indexOf(v) === i); return { totalPets: pets.length, categories: categories.slice(0, 5), sample: pets.slice(0, 3).map(p => ({ name: p.name, status: p.status })) }; `); console.log('Result:', JSON.stringify(result.result, null, 2)); } main().catch(console.error); ``` -------------------------------- ### Server Lifecycle Management Source: https://github.com/mondaycom/agent-tool-protocol/blob/master/packages/server/README.md Demonstrates the core server lifecycle: creation, setup with providers and API groups, starting the server, and graceful shutdown. ```APIDOC ## Server Lifecycle ```typescript const server = createServer(config); // Setup server.setCacheProvider(cache); server.setAuthProvider(auth); server.addAPIGroup(apiGroup); server.use(middleware); // Start await server.start(3333); // Shutdown await server.shutdown(); ``` ``` -------------------------------- ### Install @mondaydotcomorg/atp-client Source: https://github.com/mondaycom/agent-tool-protocol/blob/master/packages/client/README.md Install the client library using npm. ```bash npm install @mondaydotcomorg/atp-client ``` -------------------------------- ### Install Dependencies Source: https://github.com/mondaycom/agent-tool-protocol/blob/master/examples/client-tools/README.md Navigate to the client-tools directory and install npm dependencies. ```bash cd examples/client-tools npm install ``` -------------------------------- ### Run LangChain Examples with Test Server Source: https://github.com/mondaycom/agent-tool-protocol/blob/master/examples/test-server/README.md Instructions for running LangChain examples concurrently with the ATP test server. This involves starting the server in one terminal and running the LangChain examples in another. ```bash # Terminal 1: Start test server cd examples/test-server NODE_OPTIONS='--no-node-snapshot' npx tsx server.ts # Terminal 2: Run LangChain examples cd examples/langchain-react-agent export OPENAI_API_KEY=sk-... yarn discover ``` -------------------------------- ### Running In-Process ATP Examples Source: https://github.com/mondaycom/agent-tool-protocol/blob/master/examples/in-process/README.md Provides commands to run the basic and multi-instance ATP examples using ts-node. Ensure you have ts-node installed globally or locally. ```bash # Basic example npx ts-node index.ts ``` ```bash # Multi-instance example (shows parallel instances) npx ts-node multi-instance.ts ``` -------------------------------- ### Run Webhook Approval Example Source: https://github.com/mondaycom/agent-tool-protocol/blob/master/examples/vercel-ai-sdk-example/README.md Execute the webhook approval example for a production-ready asynchronous approval pattern. ```bash npm run webhook ``` -------------------------------- ### Install @mondaydotcomorg/atp-mcp-adapter Source: https://github.com/mondaycom/agent-tool-protocol/blob/master/packages/mcp-adapter/README.md Install the package using npm. ```bash npm install @mondaydotcomorg/atp-mcp-adapter ``` -------------------------------- ### Install @mondaydotcomorg/atp-vercel-ai-sdk Source: https://github.com/mondaycom/agent-tool-protocol/blob/master/packages/vercel-ai-sdk/README.md Install the SDK and its dependencies using npm. ```bash npm install @mondaydotcomorg/atp-vercel-ai-sdk ai @ai-sdk/openai ``` -------------------------------- ### Install @mondaydotcomorg/atp-provenance Source: https://github.com/mondaycom/agent-tool-protocol/blob/master/packages/provenance/README.md Install the package using npm. ```bash npm install @mondaydotcomorg/atp-provenance ``` -------------------------------- ### Install Dependencies for Google Calendar Agent Source: https://github.com/mondaycom/agent-tool-protocol/blob/master/examples/google-calendar-agent/SETUP.md Installs all project dependencies from the monorepo root and then navigates to the Google Calendar agent example directory. Ensure you are in the monorepo root before running. ```bash cd /Users/galli/Development/agent-tool-protocol-public yarn install cd examples/google-calendar-agent ``` -------------------------------- ### Install @mondaydotcomorg/atp-providers Source: https://github.com/mondaycom/agent-tool-protocol/blob/master/packages/providers/README.md Install the package using npm. ```bash npm install @mondaydotcomorg/atp-providers ``` -------------------------------- ### Run LangChain React Agent Example Source: https://github.com/mondaycom/agent-tool-protocol/blob/master/README.md Execute an advanced LangChain agent with the test server. This involves starting the test server first, then running the agent. Set the OPENAI_API_KEY environment variable. ```bash # Start test server cd examples/test-server npx tsx server.ts # Run agent cd examples/langchain-react-agent export OPENAI_API_KEY=sk-... npm start ``` -------------------------------- ### Install @mondaydotcomorg/atp-runtime Source: https://github.com/mondaycom/agent-tool-protocol/blob/master/packages/runtime/README.md Install the package using npm. ```bash npm install @mondaydotcomorg/atp-runtime ``` -------------------------------- ### Run Basic Agent Example Source: https://github.com/mondaycom/agent-tool-protocol/blob/master/examples/vercel-ai-sdk-example/README.md Execute the basic agent example which includes CLI approval for operations. ```bash npm run agent ``` -------------------------------- ### Install Project Dependencies Source: https://github.com/mondaycom/agent-tool-protocol/blob/master/__tests__/e2e/README.md Navigate to the project directory and install all necessary dependencies using yarn. ```bash cd /Users/galli/Development/agent-tool-protocol yarn install ``` -------------------------------- ### Install Prerelease Package by Tag Source: https://github.com/mondaycom/agent-tool-protocol/blob/master/docs/publishing.md Install a prerelease version of the package using the 'rc' tag. ```bash npm install @mondaydotcomorg/atp-server@rc ``` -------------------------------- ### Install @mondaydotcomorg/atp-server Source: https://github.com/mondaycom/agent-tool-protocol/blob/master/packages/server/README.md Install the ATP server package using npm. ```bash npm install @mondaydotcomorg/atp-server ``` -------------------------------- ### Set API Keys and Run Server Source: https://github.com/mondaycom/agent-tool-protocol/blob/master/examples/production-example/README.md Configure API keys using environment variables and start the server. Optional for development. ```bash export ATP_API_KEYS="key1,key2,key3" tsx server.ts ``` -------------------------------- ### Run Streaming Example Source: https://github.com/mondaycom/agent-tool-protocol/blob/master/examples/vercel-ai-sdk-example/README.md Execute the streaming example to demonstrate real-time output using Vercel AI SDK's streamText. ```bash npm run streaming ``` -------------------------------- ### Install Dependencies Source: https://github.com/mondaycom/agent-tool-protocol/blob/master/examples/simple-code-agent/README.md Install the necessary Node.js packages for the agent. ```bash npm install ``` -------------------------------- ### Install @mondaydotcomorg/atp-protocol Source: https://github.com/mondaycom/agent-tool-protocol/blob/master/packages/protocol/README.md Install the Agent Tool Protocol package using npm. ```bash npm install @mondaydotcomorg/atp-protocol ``` -------------------------------- ### Install @mondaydotcomorg/atp-compiler Source: https://github.com/mondaycom/agent-tool-protocol/blob/master/packages/atp-compiler/README.md Install the ATP compiler package using npm. ```bash npm install @mondaydotcomorg/atp-compiler ``` -------------------------------- ### MCPConnector (stdio) Examples Source: https://github.com/mondaycom/agent-tool-protocol/blob/master/packages/mcp-adapter/README.md Examples of connecting to a filesystem MCP server and a custom Python MCP server using stdio. ```typescript // Filesystem MCP server const filesystem = await connector.connectToMCPServer({ name: 'files', command: 'npx', args: ['-y', '@modelcontextprotocol/server-filesystem', '/data'], }); // Custom Python MCP server const custom = await connector.connectToMCPServer({ name: 'custom', command: 'python', args: ['mcp_server.py'], env: { API_KEY: process.env.API_KEY, }, }); ``` -------------------------------- ### Install @mondaydotcomorg/atp-langchain Source: https://github.com/mondaycom/agent-tool-protocol/blob/master/packages/langchain/README.md Install the necessary packages for LangChain and LangGraph integration with ATP. ```bash npm install @mondaydotcomorg/atp-langchain @langchain/core @langchain/langgraph ``` -------------------------------- ### Install Dependencies Source: https://github.com/mondaycom/agent-tool-protocol/blob/master/examples/monday-graphql/README.md Install project dependencies using yarn. ```bash yarn install ``` -------------------------------- ### Copy Environment Template Source: https://github.com/mondaycom/agent-tool-protocol/blob/master/examples/google-calendar-agent/auth/README.md Copy the example environment file to create your project's .env file. Ensure this is done from the project root. ```bash # From the project root (google-calendar-agent/) cp auth/env.example .env ``` -------------------------------- ### Environment Variables Setup Source: https://github.com/mondaycom/agent-tool-protocol/blob/master/examples/vercel-ai-sdk-example/README.md Configure environment variables for API keys and server URLs. ```bash OPENAI_API_KEY=your-openai-api-key ATP_SERVER_URL=http://localhost:3333 ATP_API_KEY=test-key ``` -------------------------------- ### Start ATP Test Server Source: https://github.com/mondaycom/agent-tool-protocol/blob/master/examples/test-server/README.md Use this command to start the ATP test server. Ensure NODE_OPTIONS is set to '--no-node-snapshot' to prevent segmentation faults. ```bash NODE_OPTIONS='--no-node-snapshot' npx tsx server.ts ``` -------------------------------- ### OAuth Integration Example Source: https://github.com/mondaycom/agent-tool-protocol/blob/master/packages/server/README.md Example of setting up an OAuth provider (Google) and adding an API group for Gmail functionality. ```APIDOC ## OAuth Integration ```typescript import { GoogleOAuthProvider } from '@mondaydotcomorg/atp-providers'; const oauthProvider = new GoogleOAuthProvider({ clientId: process.env.GOOGLE_CLIENT_ID, clientSecret: process.env.GOOGLE_CLIENT_SECRET, redirectUri: 'http://localhost:3333/oauth/callback', scopes: ['https://www.googleapis.com/auth/userinfo.email'], }); server.addAPIGroup({ name: 'gmail', type: 'oauth', oauthProvider, functions: [ { name: 'sendEmail', description: 'Send email via Gmail', inputSchema: { /* ... */ }, handler: async (input, credentials) => { // Use credentials.accessToken return await sendGmailEmail(input, credentials.accessToken); }, }, ], }); ``` ``` -------------------------------- ### Security Policy Engine Quick Start Source: https://github.com/mondaycom/agent-tool-protocol/blob/master/packages/provenance/README.md Initialize a SecurityPolicyEngine with a list of policies and a logger. Use the `checkTool` method to verify operations before they are executed. ```APIDOC ## Security Policy Engine ### Quick Start ```typescript import { SecurityPolicyEngine, preventDataExfiltration, requireUserOrigin, } from '@mondaydotcomorg/atp-provenance'; const policyEngine = new SecurityPolicyEngine( [preventDataExfiltration, requireUserOrigin], console // Logger (pino, winston, or console) ); // Check before sensitive operations try { await policyEngine.checkTool('send', 'email', { to: 'attacker@evil.com', body: user, // Contains provenance metadata }); } catch (error) { console.error('Security policy blocked:', error.message); } ``` ``` -------------------------------- ### Start ATP Server Source: https://github.com/mondaycom/agent-tool-protocol/blob/master/examples/simple-code-agent/README.md Run this command in your terminal to start the ATP server. Ensure you are in the correct directory. ```bash cd path/to/your/atp-server npm start ``` -------------------------------- ### Install ATP Server and Client Packages Source: https://github.com/mondaycom/agent-tool-protocol/blob/master/README.md Install the ATP server and client packages using your preferred package manager. The `--no-node-snapshot` flag is recommended for Node.js 20+. ```bash # Using Yarn (recommended) yarn add @mondaydotcomorg/atp-server @mondaydotcomorg/atp-client # Using npm npm install @mondaydotcomorg/atp-server @mondaydotcomorg/atp-client # Using pnpm pnpm add @mondaydotcomorg/atp-server @mondaydotcomorg/atp-client # Using bun bun add @mondaydotcomorg/atp-server @mondaydotcomorg/atp-client ``` -------------------------------- ### Set API Key and Start Agent Source: https://github.com/mondaycom/agent-tool-protocol/blob/master/examples/langchain-quickstart/README.md Set the OpenAI API key as an environment variable and then start the agent process using npm. ```bash export OPENAI_API_KEY=sk-... npm start ``` -------------------------------- ### Install Specific Prerelease Version Source: https://github.com/mondaycom/agent-tool-protocol/blob/master/docs/publishing.md Install a specific prerelease version of the package by its full version string. ```bash npm install @mondaydotcomorg/atp-server@0.18.4-rc.0 ``` -------------------------------- ### Install ATP Core and Optional Integrations Source: https://context7.com/mondaycom/agent-tool-protocol/llms.txt Install the core ATP packages and optional integrations using yarn. Node.js 20+ may require a specific flag at startup. ```bash # Core packages yarn add @mondaydotcomorg/atp-server @mondaydotcomorg/atp-client # Optional integrations yarn add @mondaydotcomorg/atp-mcp-adapter yarn add @mondaydotcomorg/atp-langchain yarn add @mondaydotcomorg/atp-providers # Node.js 20+ requires this flag at startup # NODE_OPTIONS='--no-node-snapshot' ``` -------------------------------- ### MCPHttpConnector Example Source: https://github.com/mondaycom/agent-tool-protocol/blob/master/packages/mcp-adapter/README.md Example of connecting to a remote MCP server via HTTP with custom headers. ```typescript const api = await connector.connectToHttpServer({ name: 'remote-api', baseUrl: 'https://mcp.example.com', headers: { Authorization: 'Bearer token', 'X-API-Key': process.env.API_KEY, }, }); ``` -------------------------------- ### Run the Agent Tool Protocol Server Source: https://github.com/mondaycom/agent-tool-protocol/blob/master/examples/opentelemetry/README.md Start the Agent Tool Protocol server using tsx. ```bash yarn tsx server.ts ``` -------------------------------- ### Standard HTTP ATP Server Setup Source: https://github.com/mondaycom/agent-tool-protocol/blob/master/examples/in-process/README.md Illustrates the standard setup for an ATP server using HTTP mode, which involves binding to a specific port. This can lead to port conflicts when multiple instances run simultaneously. ```typescript const server = createServer(); await server.listen(3333); // Binds to port 3333 const client = new AgentToolProtocolClient({ baseUrl: 'http://localhost:3333' }); ``` -------------------------------- ### Set OpenAI API Key Source: https://github.com/mondaycom/agent-tool-protocol/blob/master/examples/checkpoint-recovery/README.md Before running the example, set your OpenAI API key as an environment variable. ```bash # Set your OpenAI API key export OPENAI_API_KEY=your-api-key-here ``` -------------------------------- ### Start MCP Server for Google Calendar Agent Source: https://github.com/mondaycom/agent-tool-protocol/blob/master/examples/google-calendar-agent/SETUP.md Starts the ATP Server with Google Calendar MCP Integration. This command should be run in the agent's directory. It lists available tools upon successful startup. ```bash cd examples/google-calendar-agent npm run server ``` -------------------------------- ### In-Process ATP Client-Server Setup Source: https://github.com/mondaycom/agent-tool-protocol/blob/master/examples/in-process/README.md Shows the in-process ATP setup where the client communicates directly with the server instance without needing to bind to a port. This enables multiple independent instances within the same process. ```typescript const server = createServer(); // No listen() call needed! const client = new AgentToolProtocolClient({ server }); await client.init(); ``` -------------------------------- ### Example: Create and Validate Execution Config Source: https://github.com/mondaycom/agent-tool-protocol/blob/master/packages/protocol/README.md Demonstrates creating an ExecutionConfig object and validating it using the ExecutionConfigSchema. Also shows checking the execution status. ```typescript import { type AgentToolProtocolRequest, type ExecutionConfig, ExecutionConfigSchema, ExecutionStatus, CallbackType, } from '@mondaydotcomorg/atp-protocol'; // Create execution config with validation const config: ExecutionConfig = { code: 'const result = await atp.llm.call({ prompt: "Hello" });', timeout: 30000, pausable: true, }; // Validate const validated = ExecutionConfigSchema.parse(config); // Check status if (result.status === ExecutionStatus.PAUSED) { console.log('Execution paused for callback'); } ``` -------------------------------- ### Security Policy Engine Quick Start Source: https://github.com/mondaycom/agent-tool-protocol/blob/master/packages/provenance/README.md Initialize a SecurityPolicyEngine with built-in policies and a logger. Use `checkTool` to verify operations against defined policies before execution. ```typescript import { SecurityPolicyEngine, preventDataExfiltration, requireUserOrigin, } from '@mondaydotcomorg/atp-provenance'; const policyEngine = new SecurityPolicyEngine( [preventDataExfiltration, requireUserOrigin], console // Logger (pino, winston, or console) ); // Check before sensitive operations try { await policyEngine.checkTool('send', 'email', { to: 'attacker@evil.com', body: user, // Contains provenance metadata }); } catch (error) { console.error('Security policy blocked:', error.message); } ``` -------------------------------- ### Start ATP Server Source: https://github.com/mondaycom/agent-tool-protocol/blob/master/examples/client-tools/README.md Run the ATP server process in one terminal. ```bash npm run server ``` -------------------------------- ### server.listen(port) / server.start() / server.stop() Source: https://context7.com/mondaycom/agent-tool-protocol/llms.txt Manages the lifecycle of the ATP server, including listening on a port, starting internals, and gracefully shutting down. ```APIDOC ## server.listen(port) / server.start() / server.stop() ### Description `listen()` binds the HTTP server. `start()` initializes internals without binding a port (use with `toExpress()` / `toFastify()` / `handler()`). `stop()` cleanly drains connections and flushes audit buffers. ### Methods - `listen(port: number)`: Binds the HTTP server to the specified port. - `start()`: Initializes server internals without binding a port. - `stop()`: Gracefully shuts down the server, draining connections and flushing buffers. ### Usage Examples ```typescript // Standalone server await server.listen(3333); // → prints banner; ATP ready on http://localhost:3333 // Express middleware import express from 'express'; const app = express(); app.use('/atp', server.toExpress()); app.listen(3000); // Fastify fastify.all('/atp/*', server.toFastify()); // Raw Node.js handler (e.g., Vercel) export default server.handler(); // Graceful shutdown process.on('SIGTERM', async () => { await server.stop(); }); ``` ``` -------------------------------- ### In-Memory Auth Provider Implementation Source: https://github.com/mondaycom/agent-tool-protocol/blob/master/examples/oauth-example/README.md An example implementation of an AuthProvider using a simple Map for in-memory storage. Useful for testing and simple setups without external databases. ```typescript const inMemoryStorage = new Map>(); class InMemoryAuthProvider implements AuthProvider { // ... implements all AuthProvider methods // Stores credentials in Map instead of database } ``` -------------------------------- ### Initialize Client Source: https://github.com/mondaycom/agent-tool-protocol/blob/master/examples/production-example/README.md Initialize the client by sending a POST request with client information. Requires the server to be running. ```bash curl -X POST http://localhost:3000/api/init \ -H "Content-Type: application/json" \ -d '{"clientInfo": {"name": "my-app", "version": "1.0.0"}}' ``` -------------------------------- ### Basic ATP Agent Setup and Run Source: https://github.com/mondaycom/agent-tool-protocol/blob/master/examples/utils/README.md Sets up an ATP agent with Langchain, configures tools, defines a system prompt, and runs an interactive chat session. Ensure ATP_SERVER_URL is set and replace 'your-token' with a valid authorization token. ```typescript import { ChatOpenAI } from '@langchain/openai'; import { createATPTools } from '@mondaydotcomorg/atp-langchain'; import { createReactAgent } from '@langchain/langgraph/prebuilt'; import { MemorySaver } from '@langchain/langgraph'; import { ChatFormatter, CodeExecutionHandler, InteractiveChatRunner } from '../utils'; async function main() { const formatter = new ChatFormatter(); formatter.suppressZodWarnings(); formatter.showHeader({ title: '🤖 My ATP Agent', subtitle: 'An agent that can execute code', }); const serverUrl = process.env.ATP_SERVER_URL || 'http://localhost:3334'; formatter.showConnecting(serverUrl); const llm = new ChatOpenAI({ modelName: 'gpt-4', temperature: 0, }); const { client: atpClient, tools } = await createATPTools({ serverUrl, headers: { Authorization: 'Bearer your-token' }, llm, }); formatter.showConnected(tools.length); const executeCodeTool = tools.find((t) => t.name === 'atp_execute_code'); // Build your system prompt inline with domain-specific instructions const systemPrompt = `You are a helpful assistant with access to the ATP runtime. **Available APIs:** ${atpClient.getTypeDefinitions()} **CRITICAL - Code Return Values:** - ⚠️ ALWAYS parse MCP responses with JSON.parse(result[0].text) before returning - ⚠️ Return CLEAN, PARSED objects - NOT raw MCP content arrays **When responding:** - Show clear, formatted results - Be concise and helpful`; const agent = createReactAgent({ llm, tools: [executeCodeTool!], checkpointSaver: new MemorySaver(), messageModifier: systemPrompt, }); const handler = new CodeExecutionHandler(formatter); const chatRunner = new InteractiveChatRunner(formatter, handler); await chatRunner.run({ agent, threadId: 'my-session', formatter, handler, }); } main(); ``` -------------------------------- ### Configure Environment Variables Source: https://github.com/mondaycom/agent-tool-protocol/blob/master/examples/simple-code-agent/README.md Create a .env file with your API keys and server details. Replace placeholders with your actual credentials. ```bash OPENAI_API_KEY=your-openai-api-key ATP_SERVER_URL=http://localhost:3334 ATP_AUTH_TOKEN=demo-token ``` -------------------------------- ### Start Server Only Source: https://github.com/mondaycom/agent-tool-protocol/blob/master/examples/monday-graphql/README.md Start only the ATP server without running an agent. ```bash cd examples/monday-graphql yarn start ``` -------------------------------- ### createATPTools Source: https://github.com/mondaycom/agent-tool-protocol/blob/master/packages/vercel-ai-sdk/README.md Initializes ATP tools with the provided options, returning a client and available tools. ```APIDOC ## createATPTools() ### Description Initializes ATP tools, providing a client for executing code and accessing tool definitions. It accepts various options to configure the client, including server URL, headers, model, embeddings, and approval handlers. ### Parameters #### `options` (CreateATPToolsOptions) - Required - `serverUrl` (string): The URL of the ATP server. - `headers` (Record): Optional headers for the server request. - `model` (any): The language model to use. - `embeddings` (EmbeddingProvider): Optional embedding provider. - `approvalHandler` (ApprovalHandler): Optional handler for approval requests. - `defaultExecutionConfig` (Partial): Optional default execution configuration. - `hooks` (ClientHooks): Optional client hooks. ### Returns - `ATPToolsResult`: An object containing the `client` (VercelAIATPClient) and `tools` (Record). ``` -------------------------------- ### Example Test Results Output Source: https://github.com/mondaycom/agent-tool-protocol/blob/master/__tests__/e2e/README.md This is an example of the expected output when all end-to-end tests pass. ```text PASS __tests__/e2e/checkpoint/checkpoint-recovery.test.ts PASS __tests__/e2e/security/jwt-authentication.test.ts PASS __tests__/e2e/security/multi-tenancy.test.ts PASS __tests__/e2e/security/resume-validation.test.ts PASS __tests__/e2e/security/tool-metadata.test.ts PASS __tests__/e2e/state-capture/infrastructure.test.ts Test Suites: 6 passed, 6 total Tests: XX passed, XX total ``` -------------------------------- ### Initialize ATP Runtime and Compiler Source: https://github.com/mondaycom/agent-tool-protocol/blob/master/packages/atp-compiler/README.md Illustrates the initialization of the ATP Compiler and its runtime, including setting up a cache provider for execution. ```typescript // In executor.ts import { ATPCompiler, initializeRuntime } from '@mondaydotcomorg/atp-compiler'; const compiler = new ATPCompiler(); // Before execution if (cacheProvider) { initializeRuntime({ executionId, cache: cacheProvider, }); const detection = compiler.detect(code); if (detection.needsTransform) { const transformed = compiler.transform(code); codeToExecute = transformed.code; } } ``` -------------------------------- ### Run Full Runtime Discovery Agent Source: https://github.com/mondaycom/agent-tool-protocol/blob/master/examples/langchain-react-agent/README.md Complete example showing a React agent with full runtime discovery. This demonstrates static runtime embedding, a single tool approach (execute_code), intelligent workflows using runtime APIs, and a real-world scenario for content recommendation with user analysis. It covers full runtime usage including LLM calls, caching, and approvals, with human-in-the-loop approval flows. ```bash npm run discover:full ``` -------------------------------- ### Custom OAuth Provider Example Source: https://github.com/mondaycom/agent-tool-protocol/blob/master/packages/providers/README.md Example of how to implement a custom OAuth provider by extending the OAuthProvider interface. ```APIDOC ## Custom OAuth Provider Example ### Description Example of how to implement a custom OAuth provider by extending the `OAuthProvider` interface. ### Usage ```typescript import type { OAuthProvider } from '@mondaydotcomorg/atp-protocol'; class SlackOAuthProvider implements OAuthProvider { name = 'slack'; async generateAuthUrl(config) { return `https://slack.com/oauth/v2/authorize?client_id=${config.clientId}&...`; } async handleCallback(code, config) { // Exchange code for tokens const response = await fetch('https://slack.com/api/oauth.v2.access', { method: 'POST', body: JSON.stringify({ code, client_id: config.clientId, ... }), }); const data = await response.json(); return { accessToken: data.access_token, refreshToken: data.refresh_token, expiresAt: Date.now() + data.expires_in * 1000, }; } async refreshToken(refreshToken, config) { // Implement refresh } async checkScopes(accessToken, requiredScopes) { // Verify scopes return true; } } ``` ``` -------------------------------- ### Server Lifecycle Management Source: https://github.com/mondaycom/agent-tool-protocol/blob/master/packages/server/README.md Illustrates the server lifecycle: creation with configuration, setting providers and API groups, using middleware, starting the server, and graceful shutdown. ```typescript const server = createServer(config); // Setup server.setCacheProvider(cache); server.setAuthProvider(auth); server.addAPIGroup(apiGroup); server.use(middleware); // Start await server.start(3333); // Shutdown await server.shutdown(); ``` -------------------------------- ### RAG with Embeddings Example Source: https://github.com/mondaycom/agent-tool-protocol/blob/master/packages/vercel-ai-sdk/README.md Example demonstrating Retrieval Augmented Generation (RAG) using ATP tools and embeddings. ```APIDOC ## RAG with Embeddings ### Description This example shows how to set up ATP tools with an embedding provider and use them within a `generateText` call for RAG. It involves embedding documents, searching for relevant content, and then using the LLM to answer based on the retrieved information. ### Example Usage ```typescript import { createATPTools } from '@mondaydotcomorg/atp-vercel-ai-sdk'; import { openai } from '@ai-sdk/openai'; import { embed } from 'ai'; const model = openai('gpt-4o'); const embeddings = { embed: async (text: string) => { const result = await embed({ model: openai.embedding('text-embedding-3-small'), value: text, }); return result.embedding; }, }; const { tools } = await createATPTools({ serverUrl: 'http://localhost:3333', headers: { Authorization: 'Bearer your-api-key' }, model, embeddings, }); const result = await generateText({ model, tools, maxSteps: 5, prompt: `Use ATP to: 1. Embed these documents: ["AI is...", "ML is...", "DL is..."] 2. Search for content similar to "neural networks" 3. Use atp.llm.call() to answer based on results`, }); ``` ``` -------------------------------- ### Start ATP Server Source: https://github.com/mondaycom/agent-tool-protocol/blob/master/examples/monday-graphql/README.md Start the ATP server in one terminal. This enables query logging when using the debug variant. ```bash cd examples/monday-graphql yarn start ``` ```bash cd examples/monday-graphql yarn start:debug ``` -------------------------------- ### Get Definitions Source: https://github.com/mondaycom/agent-tool-protocol/blob/master/examples/production-example/README.md Retrieve definitions by sending a GET request to the /api/definitions endpoint. Useful for understanding available tools and their schemas. ```bash curl http://localhost:3000/api/definitions ``` -------------------------------- ### Configure Cache Providers Source: https://context7.com/mondaycom/agent-tool-protocol/llms.txt Demonstrates how to instantiate and configure MemoryCache, RedisCache, and FileCache. RedisCache is recommended for production environments due to its shared nature across pods. ```typescript import { MemoryCache, RedisCache, FileCache } from '@mondaydotcomorg/atp-providers'; import Redis from 'ioredis'; // In-memory (default; not shared across pods) const memCache = new MemoryCache({ maxKeys: 5000, defaultTTL: 86400 }); // Redis (shared across pods; recommended for production) const redis = new Redis({ host: 'redis', port: 6379, password: process.env.REDIS_PASSWORD }); const redisCache = new RedisCache({ redis, keyPrefix: 'atp:', defaultTTL: 3600 }); // File-based (single-node persistence across restarts) const fileCache = new FileCache({ directory: '/var/cache/atp', defaultTTL: 3600 }); const server = createServer({ providers: { cache: redisCache } }); ``` -------------------------------- ### Environment Configuration Source: https://github.com/mondaycom/agent-tool-protocol/blob/master/examples/monday-graphql/README.md Configure environment variables for Monday.com API token and OpenAI API key. ```bash MONDAY_API_TOKEN=your_monday_token_here OPENAI_API_KEY=your_openai_key_here ``` ```bash export MONDAY_API_TOKEN=your_token_here export OPENAI_API_KEY=your_openai_key_here ``` -------------------------------- ### Clone Repository and Install Dependencies Source: https://github.com/mondaycom/agent-tool-protocol/blob/master/README.md Clone the Agent Tool Protocol repository and install its dependencies using Yarn. Node.js 18+ is required. ```bash # Clone repository git clone https://github.com/yourusername/agent-tool-protocol.git cd agent-tool-protocol # Install dependencies (Node.js 18+) yarn install ``` -------------------------------- ### Start Jaeger for Local Testing Source: https://github.com/mondaycom/agent-tool-protocol/blob/master/examples/opentelemetry/README.md Start a local Jaeger instance using Docker for testing OpenTelemetry integration. Ensure the OTLP collector is enabled. ```bash docker run -d --name jaeger \ -e COLLECTOR_OTLP_ENABLED=true \ -p 16686:16686 \ -p 4318:4318 \ jaegertracing/all-in-one:latest ``` -------------------------------- ### Load OpenAPI Spec at Runtime Source: https://github.com/mondaycom/agent-tool-protocol/blob/master/examples/runtime-openapi-loading/README.md Use `loadOpenAPI` to load specs from URLs. This method works identically whether the server is running or not. It can load specs before starting and also update them after starting. ```typescript import { createServer } from '@mondaydotcomorg/atp-server'; const server = createServer(); // Works before starting await server.loadOpenAPI('http://localhost:3040/openapi.json', { name: 'demo', }); await server.listen(3000); // Same method works after starting too! await server.loadOpenAPI('http://api.example.com/openapi.json', { name: 'another-api', filter: { methods: ['GET', 'POST'], tags: ['pets'], }, }); ``` -------------------------------- ### Start MCP Server and Test with Curl Source: https://github.com/mondaycom/agent-tool-protocol/blob/master/examples/google-calendar-agent/SETUP.md Start the MCP server in one terminal and use curl in another to test the '/tools/list' endpoint. This verifies that the server is running and returning available calendar tools. ```bash # Terminal 1: Start server npm run server # Terminal 2: Test with curl curl -X POST http://localhost:3334/tools/list \ -H "Authorization: Bearer calendar-demo-token" \ -H "Content-Type: application/json" ``` -------------------------------- ### Run the Google Calendar Agent Source: https://github.com/mondaycom/agent-tool-protocol/blob/master/examples/google-calendar-agent/SETUP.md Executes the agent using npm start. This command should be run in a separate terminal from the server. The first run will initiate an OAuth authentication flow. ```bash # In a new terminal, same directory npm start ``` -------------------------------- ### AgentToolProtocolClient Initialization and Service Provision Source: https://context7.com/mondaycom/agent-tool-protocol/llms.txt Demonstrates how to initialize the AgentToolProtocolClient in HTTP or in-process mode, manage session tokens, and provide essential client-side services such as LLM, approval, and embedding handlers. ```APIDOC ## `AgentToolProtocolClient` — client SDK Connects to an ATP server (HTTP or in-process), manages the session token, routes callbacks (LLM, approval, embedding, client tools) back from the sandbox to local handlers. ```typescript import { AgentToolProtocolClient } from '@mondaydotcomorg/atp-client'; // ── HTTP mode ─────────────────────────────────────────────────────────────── const client = new AgentToolProtocolClient({ baseUrl: 'http://localhost:3333', headers: { Authorization: 'Bearer my-api-key' }, tokenRefresh: { enabled: true, bufferMs: 5000 }, // refresh 5 s before expiry hooks: { preRequest: async (ctx) => ({ headers: { ...ctx.currentHeaders, 'X-Trace-Id': crypto.randomUUID() }, }), }, }); // ── In-process mode (no port binding — perfect for MCP stdio servers) ─────── const server = createServer(); server.use([petstore]); const client = new AgentToolProtocolClient({ server }); // no baseUrl // ── Session init ───────────────────────────────────────────────────────────── const session = await client.init({ name: 'my-agent', version: '1.0.0' }); // → { clientId, token, expiresAt, tokenRotateAt } // ── Provide client-side services ───────────────────────────────────────────── client.provideLLM({ call: async (prompt, opts) => openai.chat.completions.create({ ... }).then(r => r.choices[0].message.content!), extract: async (prompt, schema) => openai.beta.chat.completions.parse({ ... }).then(r => r.choices[0].message.parsed), classify: async (text, cats) => cats[0], // simplified }); client.provideApproval({ request: async (message, context) => { const answer = await readline.question(`Approve? "${message}" [y/N] `); return { approved: answer.toLowerCase() === 'y', timestamp: Date.now() }; }, }); client.provideEmbedding({ embed: async (text) => (await openai.embeddings.create({ model: 'text-embedding-3-small', input: text })).data[0].embedding, }); ``` ``` -------------------------------- ### Quick Start: Initialize Runtime and Compile Code Source: https://github.com/mondaycom/agent-tool-protocol/blob/master/packages/atp-compiler/README.md Initialize the ATP runtime with execution details and a cache provider, then create a compiler instance to transform user-defined asynchronous code. ```typescript import { ATPCompiler, initializeRuntime } from '@mondaydotcomorg/atp-compiler'; import { cacheProvider } from '@mondaydotcomorg/atp-protocol'; // Initialize runtime initializeRuntime({ executionId: 'exec-123', cache: cacheProvider, }); // Create compiler const compiler = new ATPCompiler({ enableBatchParallel: true, }); // Transform code const userCode = ` const items = [1, 2, 3, 4, 5]; const results = []; for (const item of items) { const response = await atp.llm.call({ prompt: `Process ${item}` }); results.push(response); } return results; `; const result = compiler.transform(userCode); // result.code now contains resumable version ``` -------------------------------- ### Webhook-Based Approval Source: https://github.com/mondaycom/agent-tool-protocol/blob/master/packages/vercel-ai-sdk/README.md Example of implementing a webhook-based approval system for ATP tools. ```APIDOC ## Webhook-Based Approval ### Description This pattern demonstrates how to handle approvals asynchronously using webhooks, suitable for production environments. It involves setting up an approval handler that records pending approvals and a webhook endpoint to receive approval/denial actions. ### Example Implementation ```typescript const pendingApprovals = new Map(); const approvalHandler = async (message: string, context?: any) => { const approvalId = generateId(); await db.approvals.create({ id: approvalId, message, context, status: 'pending', }); await sendSlackNotification({ channel: '#approvals', text: message, actions: [ { type: 'button', text: 'Approve', action_id: `approve_${approvalId}` }, { type: 'button', text: 'Deny', action_id: `deny_${approvalId}` }, ], }); return new Promise((resolve) => { pendingApprovals.set(approvalId, resolve); setTimeout(() => { pendingApprovals.delete(approvalId); resolve(false); }, 300000); }); }; app.post('/slack/actions', async (req, res) => { const { action_id } = req.body; const approvalId = action_id.replace(/^(approve|deny)_/, ''); const approved = action_id.startsWith('approve'); const resolve = pendingApprovals.get(approvalId); if (resolve) { resolve(approved); pendingApprovals.delete(approvalId); } res.json({ ok: true }); }); ``` ``` -------------------------------- ### Get All Provenance Source: https://github.com/mondaycom/agent-tool-protocol/blob/master/packages/provenance/README.md Use `getAllProvenance` to retrieve all provenance metadata associated with a value. ```typescript getAllProvenance(value: unknown): ProvenanceMetadata[] ``` -------------------------------- ### Google Calendar Agent Output Example Source: https://github.com/mondaycom/agent-tool-protocol/blob/master/examples/google-calendar-agent/SETUP.md Illustrates the expected output when the Google Calendar agent runs successfully, including connection confirmation, tool availability, reasoning steps, tool calls, and completion messages. ```text 📅 Google Calendar Scheduling Agent ✅ Connected! Available tools: 7 📋 Calendar Tools: • list-calendars • get-freebusy • create-event ... 🎬 Agent execution started... 🤔 Agent Reasoning (Step 1): I need to check calendar availability... 🔧 Tool Call: list-calendars { "calendars": [ {"id": "primary", "summary": "John Doe"} ] } 🔧 Tool Call: get-freebusy ... ✅ Meeting scheduling completed! ``` -------------------------------- ### Set up Google OAuth Credentials Source: https://github.com/mondaycom/agent-tool-protocol/blob/master/examples/google-calendar-agent/README.md Follow these steps to set up Google OAuth credentials for the agent. This involves copying an environment template, editing the .env file with your API keys and credentials path, and generating an OAuth token. ```bash # Copy environment template cp auth/env.example .env # Edit .env and add: # - OPENAI_API_KEY=your-openai-api-key # - GOOGLE_OAUTH_CREDENTIALS=/path/to/gcp-oauth.keys.json # Generate OAuth token (opens browser) npm run auth ``` -------------------------------- ### MemoryCache Source: https://github.com/mondaycom/agent-tool-protocol/blob/master/packages/providers/README.md In-memory cache for development and testing. Provides basic set, get, and delete operations. ```APIDOC ## MemoryCache ### Description In-memory cache for development and testing. ### Usage ```typescript import { MemoryCache } from '@mondaydotcomorg/atp-providers'; const cache = new MemoryCache({ defaultTTL: 3600, // 1 hour maxSize: 1000, // Max entries }); await cache.set('key', value, 3600); const cached = await cache.get('key'); await cache.delete('key'); ``` ### Methods - **set(key: string, value: any, ttl?: number): Promise** - **get(key: string): Promise** - **delete(key: string): Promise** ```