# How to integrate Esputnik MCP with OpenAI Agents SDK

```json
{
  "title": "How to integrate Esputnik MCP with OpenAI Agents SDK",
  "toolkit": "Esputnik",
  "toolkit_slug": "esputnik",
  "framework": "OpenAI Agents SDK",
  "framework_slug": "open-ai-agents-sdk",
  "url": "https://composio.dev/toolkits/esputnik/framework/open-ai-agents-sdk",
  "markdown_url": "https://composio.dev/toolkits/esputnik/framework/open-ai-agents-sdk.md",
  "updated_at": "2026-05-12T10:10:38.753Z"
}
```

## Introduction

This guide walks you through connecting Esputnik to the OpenAI Agents SDK using the Composio tool router. By the end, you'll have a working Esputnik agent that can bulk add 500 new email contacts, delete sms message template with id 123, get status of yesterday's contact import through natural language commands.
This guide will help you understand how to give your OpenAI Agents SDK agent real control over a Esputnik account through Composio's Esputnik MCP server.
Before we dive in, let's take a quick look at the key ideas and tools involved.

## Also integrate Esputnik with

- [Claude Agent SDK](https://composio.dev/toolkits/esputnik/framework/claude-agents-sdk)
- [Claude Code](https://composio.dev/toolkits/esputnik/framework/claude-code)
- [Claude Cowork](https://composio.dev/toolkits/esputnik/framework/claude-cowork)
- [Codex](https://composio.dev/toolkits/esputnik/framework/codex)
- [OpenClaw](https://composio.dev/toolkits/esputnik/framework/openclaw)
- [Hermes](https://composio.dev/toolkits/esputnik/framework/hermes-agent)
- [CLI](https://composio.dev/toolkits/esputnik/framework/cli)
- [Google ADK](https://composio.dev/toolkits/esputnik/framework/google-adk)
- [LangChain](https://composio.dev/toolkits/esputnik/framework/langchain)
- [Vercel AI SDK](https://composio.dev/toolkits/esputnik/framework/ai-sdk)
- [Mastra AI](https://composio.dev/toolkits/esputnik/framework/mastra-ai)
- [LlamaIndex](https://composio.dev/toolkits/esputnik/framework/llama-index)
- [CrewAI](https://composio.dev/toolkits/esputnik/framework/crew-ai)

## TL;DR

Here's what you'll learn:
- Get and set up your OpenAI and Composio API keys
- Install the necessary dependencies
- Initialize Composio and create a Tool Router session for Esputnik
- Configure an AI agent that can use Esputnik as a tool
- Run a live chat session where you can ask the agent to perform Esputnik operations

## What is OpenAI Agents SDK?

The OpenAI Agents SDK is a lightweight framework for building AI agents that can use tools and maintain conversation state. It provides a simple interface for creating agents with hosted MCP tool support.
Key features include:
- Hosted MCP Tools: Connect to external services through hosted MCP endpoints
- SQLite Sessions: Persist conversation history across interactions
- Simple API: Clean interface with Agent, Runner, and tool configuration
- Streaming Support: Real-time response streaming for interactive applications

## What is the Esputnik MCP server, and what's possible with it?

The Esputnik MCP server is an implementation of the Model Context Protocol that connects your AI agent and assistants like Claude, Cursor, etc directly to your Esputnik account. It provides structured and secure access to your marketing automation tools, so your agent can perform actions like sending broadcasts, managing contacts, importing data, and handling push notifications on your behalf.
- Bulk contact import and management: Quickly add or update thousands of contacts at once, check import status, and keep your lists up to date with minimal effort.
- Broadcast and message control: Retrieve, review, and manage your marketing broadcasts and app inbox messages, ensuring your campaigns run smoothly.
- Order and transactional data automation: Import and synchronize large batches of order data, keeping your marketing segmentation and triggers accurate and relevant.
- Push and SMS notification management: Activate or deactivate push tokens, delete outdated SMS templates, and fine-tune your notification workflows directly through your agent.
- Domain and integration setup: Register domains for web tracking or widgets, helping you expand and customize your communication reach seamlessly.

## Supported Tools

| Tool slug | Name | Description |
|---|---|---|
| `ESPUTNIK_ADD_CONTACT` | Add Contact | Tool to create or update a single contact in eSputnik in real-time. Use when you need to add a new contact or update an existing one by matching on channels. If a contact with the same channel (email, sms, etc.) already exists, it will be updated. Otherwise, a new contact is created. New contacts are treated as confirmed (double opt-in assumed). For bulk operations with 2+ contacts, use the Bulk Add or Update Contacts action instead. |
| `ESPUTNIK_ADD_DOMAIN` | Add Domain | Register a domain with eSputnik for web tracking, widgets, or web push notifications. This tool is used to add a new domain to your eSputnik account, enabling: - Website behavior tracking for personalization - Widget integration (pop-ups, subscription forms) - Web push notification configuration Prerequisites: - Valid eSputnik API credentials with appropriate permissions - Domain ownership or administrative access to configure tracking Returns the registered domain and associated site identifier. |
| `ESPUTNIK_ADD_ORDERS` | Add Orders Bulk | Tool to transfer orders in bulk to eSputnik. Use when you need to import up to 1000 orders at once. |
| `ESPUTNIK_ADD_UNSUBSCRIBED_EMAILS` | Add Unsubscribed Emails | Tool to add email addresses to the list of unsubscribed contacts. Use when you need to unsubscribe contacts from receiving emails. |
| `ESPUTNIK_ADD_WEBPUSH_DOMAIN` | Add Web Push Domain | Tool to add a domain for web push notifications in eSputnik. Use when you need to register a new domain to enable web push notification functionality. The domain must be reachable and not already registered in your account. This operation configures the service worker settings required for web push notifications to function. Prerequisites: - Valid eSputnik API credentials with appropriate permissions - Domain ownership or administrative access - Service worker JavaScript file prepared for deployment |
| `ESPUTNIK_ATTACH_CONTACTS_TO_SEGMENT` | Attach Contacts to Segment | Tool to attach contacts to a static segment (group) by contact IDs or external customer IDs. Use this action to add contacts to a static segment for organizing and targeting your contact lists. You can specify contacts using either eSputnik internal contact IDs or your own external customer IDs. Maximum 500 contacts per request. |
| `ESPUTNIK_BULK_ADD_OR_UPDATE_CONTACTS` | Bulk Add or Update Contacts | Bulk add or update up to 3000 contacts in eSputnik asynchronously. Use this action to import multiple contacts at once or synchronize your CRM contact list. Contacts are matched by the channel specified in dedupeOn (email, sms, or mobilepush). If a contact exists, it is updated; otherwise, a new contact is created. Returns an asyncSessionId that can be used with the Get Contact Import Status action to monitor import progress. Note: New contacts created via this method are treated as confirmed (double opt-in assumed). |
| `ESPUTNIK_CHANGE_TOKEN_ACTIVITY` | Change Mobile Push Token Activity | Activate or deactivate a mobile push notification token in eSputnik. Use this action to control whether a specific device token can receive push notifications. When a token is deactivated, the device will not receive push notifications until reactivated. Common use cases: - Temporarily disable notifications for a user's device - Reactivate a previously disabled token - Manage notification preferences at the device level Note: The app_uuid and token_id must correspond to a token that has been previously registered in eSputnik via the mobile SDK or API. |
| `ESPUTNIK_CREATE_API_TOKEN` | Create API Token | Generate a new API token for authentication. Use this action to create an API token using your eSputnik account credentials. The token can be used for authenticating subsequent API requests. This action requires basic authentication (username and password) which is automatically provided from your configured credentials. Returns a string token that should be used in the Authorization header for future API calls. This is particularly useful when you need to generate fresh tokens or when integrating eSputnik API with other systems. |
| `ESPUTNIK_CREATE_APP_INBOX_MESSAGE` | Create App Inbox Message | Tool to create a basic App Inbox message in eSputnik. Use when you need to create a new in-app notification message. App Inbox messages are displayed within mobile apps or websites as notifications to users. Requires at minimum a name, title, and text. Optionally supports images, links, custom data, translations for multiple languages, tags, and subscription categories. |
| `ESPUTNIK_CREATE_CONTACTS_FILE` | Create Contacts from File | Import or update contacts from an external file in eSputnik. Creates new contacts and updates existing ones based on dedupeOn field. Use this action to bulk import contacts from a CSV file hosted at a publicly accessible URL. The file must use comma delimiters and follow eSputnik's column naming requirements (firstName, lastName, email, sms, etc.). The import is asynchronous - use the returned asyncSessionId with Get Contact Import Status to monitor progress. |
| `ESPUTNIK_CREATE_EMAIL_MESSAGE` | Create Email Message | Tool to create or update an email message in eSputnik. Use when you need to add a new email template or update an existing one, including support for multilingual message versions. When 'id' is provided in the request, the action updates the existing message with that ID. When 'id' is omitted, a new email message is created. The 'languageCode' parameter allows adding or updating specific language versions for multilingual campaigns. |
| `ESPUTNIK_CREATE_MOBILE_PUSH_MESSAGE` | Create Mobile Push Message | Tool to create a new mobile push notification message in eSputnik. Use when you need to set up a push notification campaign for mobile app users. The created message can include title, body text, images, action buttons, and custom data. Supports multilingual messages through the translations field. After creation, use the returned message ID to send the notification to specific contacts or segments. |
| `ESPUTNIK_CREATE_SMS_MESSAGE` | Create SMS Message | Tool to create a basic SMS message template in eSputnik. Use when you need to create a new SMS message template for sending campaigns. The created template can be used later for sending SMS messages to contacts. Before creating an SMS message, ensure you have configured SMS interfaces (sender names) in your eSputnik account. |
| `ESPUTNIK_CREATE_TELEGRAM_MESSAGE` | Create Telegram Message | Create a basic Telegram bot message in eSputnik. Use when you need to create a new message template that can be sent to contacts via Telegram. The message is saved as a template in eSputnik and can later be sent to contacts using the Send Message API. The message ID returned in the response is required for sending operations. Prerequisites: - Valid eSputnik API credentials with write permissions - Telegram bot configured in your eSputnik account Example usage: "Create a Telegram message with name 'Welcome Message' and text 'Hello!'" |
| `ESPUTNIK_DELETE_APP_INBOX_MESSAGE` | Delete App Inbox Message | Tool to delete an App Inbox message by its ID from eSputnik. Use when you need to permanently remove an App Inbox message that is no longer needed. |
| `ESPUTNIK_DELETE_APPINBOX_TRANSLATION` | Delete App Inbox Translation | Delete a language translation of an App Inbox message from eSputnik. Use this action to remove a specific language version of an App Inbox message while keeping the base message and other translations intact. This is useful when you no longer need to support a particular language or need to clean up outdated translations. Prerequisites: - The App Inbox message must exist - The specified language translation must exist for the message - Valid eSputnik API credentials with write permissions |
| `ESPUTNIK_DELETE_BROADCAST` | Delete Broadcast | Tool to cancel a scheduled broadcast campaign. Use when you need to stop a broadcast from being sent. |
| `ESPUTNIK_DELETE_CONTACT` | Delete Contact | Tool to delete a contact by its Yespo ID. Use when you need to remove a contact with no pending interactions. |
| `ESPUTNIK_DELETE_CONTACT_BY_EXTERNAL_ID` | Delete Contact by External ID | Delete a contact from eSputnik using their external customer ID. Use this tool when you need to remove a contact identified by the externalCustomerId (the unique ID from your external system, e.g., CRM or database). This is useful when you don't have the eSputnik internal contact ID but do have the external reference. For GDPR compliance, set erase=true to permanently remove all contact data including activity history and tracking data. |
| `ESPUTNIK_DELETE_EMAIL_MESSAGE` | Delete Email Message | Delete a basic email message by its ID from eSputnik. Use this action to permanently remove an email message that is no longer needed. This is a destructive operation - the message will be permanently deleted and cannot be recovered. Prerequisites: - The email message must exist - Valid eSputnik API credentials with write permissions Example usage: "Delete email message 2345678", "Remove email with ID 12345" |
| `ESPUTNIK_DELETE_EMAIL_TRANSLATION` | Delete Email Translation | Delete a translation of a base email message from eSputnik. Use this action to remove a specific language translation of an email message template. This does not delete the base email message, only the specified translation. The operation is permanent and the translation cannot be recovered once deleted. Prerequisites: - The email message must exist - The specified language translation must exist - Valid eSputnik API credentials with write permissions Example usage: "Delete Spanish translation of email 4404258", "Remove French translation for email message 12345" |
| `ESPUTNIK_DELETE_MOBILEPUSH_MESSAGE` | Delete Mobile Push Message | Delete a base Mobile Push message by its ID from eSputnik. Use this action to permanently remove a Mobile Push message that is no longer needed. This is a destructive operation - the message will be permanently deleted and cannot be recovered. Prerequisites: - The Mobile Push message must exist - Valid eSputnik API credentials with write permissions Example usage: "Delete Mobile Push message 4404238", "Remove push notification with ID 2345678" |
| `ESPUTNIK_DELETE_MOBILEPUSH_TRANSLATION` | Delete Mobile Push Translation | Delete a language version of a base Mobile Push message from eSputnik. Use this tool to remove a specific language translation from a mobile push message while keeping the base message and other translations intact. This is useful when managing multilingual campaigns and needing to remove or update specific language versions. |
| `ESPUTNIK_DELETE_ORDERS` | Delete Orders | Tool to schedule asynchronous deletion of orders in eSputnik. Use when you need to delete orders by external ID or by date range. Deletion can be performed by: - Specific order: Provide externalOrderId to delete a single order - Date range: Provide both 'from' and 'to' parameters to delete all orders within the specified period The deletion is asynchronous - the API accepts the request and processes it in the background. |
| `ESPUTNIK_DELETE_SMS_MESSAGE` | Delete SMS Message | Delete a base SMS message template by its ID from eSputnik. Use this action to permanently remove an SMS message template that is no longer needed. This is a destructive operation - the template will be permanently deleted and cannot be recovered. Prerequisites: - The SMS message template must exist - Valid eSputnik API credentials with write permissions Example usage: "Delete SMS template 12345", "Remove SMS message with ID 67890" |
| `ESPUTNIK_DELETE_SMS_TRANSLATION` | Delete SMS Translation | Delete a language version of a base SMS message from eSputnik. Use this action to remove a specific language translation of an SMS message while keeping the base message and other translations intact. This is useful for removing outdated or incorrect translations. Prerequisites: - The base SMS message must exist - The specified language translation must exist for that message - Valid eSputnik API credentials with write permissions Example usage: "Delete Spanish translation of SMS message 4404242", "Remove French version of SMS 12345" |
| `ESPUTNIK_DELETE_TELEGRAM_MESSAGE` | Delete Telegram Message | Delete a base Telegram bot message by its ID from eSputnik. Use this action to permanently remove a Telegram bot message that is no longer needed. This is a destructive operation - the message will be permanently deleted and cannot be recovered. Prerequisites: - The Telegram bot message must exist - Valid eSputnik API credentials with write permissions Example usage: "Delete Telegram message 4404236", "Remove Telegram bot message with ID 12345" |
| `ESPUTNIK_DELETE_TELEGRAM_TRANSLATION` | Delete Telegram Translation | Delete a language version of a Telegram bot message from eSputnik. Use this action to remove a specific language translation of a Telegram bot message while keeping the base message and other translations intact. This is useful for managing multilingual bot messages when a translation is no longer needed or needs to be recreated. |
| `ESPUTNIK_DETACH_CONTACTS_FROM_SEGMENT` | Detach Contacts from Segment | Tool to delete contacts from a static segment by contact IDs or external customer IDs. Use when you need to remove specific contacts from a segment or clear an entire segment. IMPORTANT: If neither contactIds nor externalCustomerIds are specified, ALL contacts will be deleted from the segment. Maximum 500 IDs per request. |
| `ESPUTNIK_GENERATE_EVENT_V2` | Generate Event V2 | Tool to send backend events from websites and mobile apps to eSputnik. Use when tracking user actions, page views, or custom events for marketing automation and analytics. Secure for sensitive data with maximum 20 KB event data limit. |
| `ESPUTNIK_GENERATE_EVENT_V3` | Generate Event V3 | Tool to generate events in eSputnik v3 API. Use when you need to track custom events for contacts (e.g., purchase, cart abandoned, page viewed). Events can be used to trigger automated campaigns and for creating dynamic content in messages. Each event must have an eventTypeKey identifier. Contact identification must be provided in the params object using standard contact identifiers (email, phone, or externalCustomerId). Additional event parameters can also be included in params. Note: This is the v3 API endpoint. For legacy integrations, v1 is available but deprecated. |
| `ESPUTNIK_GENERATE_PAST_EVENTS_V2` | Generate Past Events V2 | Tool to transfer past event data from your CRM or data store to eSputnik using v2 API. Use when you need to import historical events that should not trigger workflows. This method allows sending up to 500 events per request with a maximum content size of 20KB. Version 2 API methods do not require escaping in nested JSON, making it easier to work with complex event parameters. Workflows are not launched for these historical events. |
| `ESPUTNIK_GENERATE_PAST_EVENTS_V3` | Generate Past Events V3 | Tool to generate past events in eSputnik v3 API. Use when you need to create historical events for contacts with specific timestamps. This action allows you to import past events with their original occurrence timestamps. Events can be used to trigger automated campaigns and for creating dynamic content in messages. Each event must have an eventTypeKey identifier and a keyValue for contact identification. |
| `ESPUTNIK_GET_ACCOUNT_INFO` | Get Account Info | Retrieve basic eSputnik account information. Use this tool to verify API authentication and get account details including the username/email and organization name. This is useful for confirming that API credentials are valid and retrieving account identifiers. Returns: - User email or username associated with the API key - Organization name for the authenticated account No parameters required - uses the authenticated account credentials automatically. This is a read-only, idempotent operation that can be called multiple times safely. |
| `ESPUTNIK_GET_APP_INBOX_MESSAGE` | Get App Inbox Message | Retrieves an App Inbox message by its unique identifier from eSputnik. Use this tool to fetch message content, metadata, and localized translations before sending, editing, or reviewing an App Inbox notification. Returns complete message details including title, text, images, links, and custom data for all configured language versions. Rate limit: 500 requests per hour. |
| `ESPUTNIK_GET_BROADCASTS` | Get Broadcasts | Retrieve a paginated list of broadcast campaigns from eSputnik. Use this tool to: - List all scheduled or sent broadcast campaigns - Check broadcast details including target segments and scheduling - Navigate through broadcasts using pagination (startindex + maxrows) Returns broadcast details including IDs, titles, message templates, target segments, and scheduling information. Results are paginated - use startindex and maxrows to navigate through large lists. No filtering parameters supported - returns all broadcasts sorted by the API's default order. |
| `ESPUTNIK_GET_CONTACT` | Get Contact | Retrieve complete information about a contact by their ID. This action returns all available information about a specific contact identified by their internal eSputnik contact ID. The response includes communication channels (email, SMS, mobilepush), profile information (name, address), and any custom fields. Use this action when you need to: - Fetch current contact details for verification or display - Check contact profile information before updating - Retrieve custom field values for a specific contact - Verify contact existence in the system Returns a 404 error if the contact ID does not exist. |
| `ESPUTNIK_GET_CONTACT_EMAILS` | Get Contact Emails | Tool to retrieve email addresses of contacts by their contact IDs. Use when you need to fetch email addresses for specific contacts using their internal eSputnik identifiers. The API returns email addresses for all valid contact IDs provided. If a contact ID doesn't exist, it will be omitted from the results (no error raised). |
| `ESPUTNIK_GET_CONTACT_IMPORT_STATUS` | Get Contact Import Status | Retrieve the status of a contact import session in eSputnik. Use this action to check the progress of an asynchronous bulk contact import operation. After calling Bulk Add or Update Contacts, use the returned asyncSessionId with this action to monitor the import status. The status field indicates the current state: - STARTED: Import has been initiated - IMPORTING: Import is in progress - FINISHED: Import completed successfully - ERROR: Import failed When finished, the mapping field contains the dedupeValue-to-contactId mappings for all successfully imported contacts. |
| `ESPUTNIK_GET_CONTACT_MESSAGE_HISTORY` | Get Contact Message History | Retrieve a contact's message history across multiple channels from eSputnik. This action returns message history for a specific contact, supporting multiple media types: Email, SMS, Viber, Mobile Push, Web Push, App Inbox, and Telegram. Use this when you need to: - Review all messages sent to a contact within a date range - Track message delivery status and engagement metrics - Audit communication history for compliance or support purposes - Filter messages by specific channel types At least one contact identifier (contactId, externalCustomerId, email, or phone) must be provided. Results are paginated using offset and maxrows parameters. |
| `ESPUTNIK_GET_CONTACTS` | Get Contacts | Search for contacts in eSputnik using various filter criteria. Use this action to find contacts by email, phone number, name, external ID, or retrieve all contacts with pagination. Returns up to 500 contacts per request. The response includes contact details such as contactId, channels, custom fields, and segment membership. Use this when you need to: - Find a contact by email or phone number - Retrieve contacts by your external system ID - List all contacts with pagination (use startindex and maxrows) - Get contact details including their segments and custom fields For searches without filter conditions, use sortBy='contactId' for faster results. Check the total_count field to determine if there are more results beyond the 500 limit. |
| `ESPUTNIK_GET_CONTACT_SUBSCRIPTIONS` | Get Contact Subscriptions | Retrieve all subscription categories a contact is enrolled in. This action returns the list of subscription categories (communication types) that a specific contact has opted into within your eSputnik account. Subscription categories typically represent different types of communications like newsletters, promotions, transactional emails, etc. Use this action when you need to: - Check which communication types a contact has subscribed to - Verify a contact's subscription preferences before sending campaigns - Audit contact subscription status for compliance purposes - Build conditional logic based on subscription preferences Returns an empty array if the contact exists but has no active subscriptions. Returns a 404 error if the contact ID does not exist in the system. |
| `ESPUTNIK_GET_EMAIL_INTERFACES` | Get Email Interfaces | Tool to retrieve all configured email interfaces (sender names) from eSputnik. Use when you need to list available email sender addresses/names before sending campaigns or messages. Returns a list of all email sender interfaces configured for the organization, including sender names, email addresses, and their active status. This information is useful when setting up email campaigns to ensure valid sender interfaces are used. |
| `ESPUTNIK_GET_EMAIL_MESSAGE` | Get Email Message | Retrieves an email message by its unique identifier from eSputnik. Use this tool to fetch message content, title, and sender details before sending, editing, or reviewing an email. Returns complete message details including HTML content, CSS styles, subject line, and sender information with html and css separated for easy manipulation. Rate limit: 500 requests per hour. |
| `ESPUTNIK_GET_EMAIL_VIEW_LINK` | Get Email View Link | Get a link to view an email message in browser from eSputnik. Use this action to retrieve a public URL that displays the email message content in a web browser. This is useful for sharing email previews, testing message rendering, or providing a web version of the email to recipients. Rate limit: 500 requests per hour (default). |
| `ESPUTNIK_GET_MESSAGE_STATUS` | Get Message Status | Retrieve delivery status for sent messages across all channels (email, SMS, Viber, push). Use this tool to track message delivery after sending messages via eSputnik API. Provide comma-separated message IDs returned from send operations to check their current delivery status, including whether messages were delivered, failed, or are still pending. This is useful for: - Verifying message delivery success or failure - Tracking message lifecycle through the delivery pipeline - Debugging failed message deliveries with error codes - Monitoring campaign message status in real-time Returns detailed status for each requested message ID, including delivery state, timestamps, and error information if applicable. |
| `ESPUTNIK_GET_MOBILE_PUSH_MESSAGE` | Get Mobile Push Message | Retrieves a mobile push message by its unique identifier from eSputnik. Use this tool to fetch message content, metadata, and language versions before sending, editing, or reviewing a mobile push notification. Returns complete message details including title, text, time-to-live settings, and sound preferences. Rate limit: 500 requests per hour. |
| `ESPUTNIK_GET_ORGANIZATION_BALANCE` | Get Organization Balance | Retrieve the current eSputnik organization balance. Use this tool to check the account's available funds, credit limit, and bonus resources (emails and SMS) before planning or sending campaigns. This helps ensure sufficient balance is available for marketing activities. Returns: - Current balance amount and currency (ISO 4217 format like USD, EUR, UAH) - Credit limit available - Number of bonus emails available - Number of bonus SMS messages available No parameters required - uses the authenticated account credentials automatically. This is a read-only, idempotent operation that can be called multiple times safely. |
| `ESPUTNIK_GET_ORGANIZATION_BILLING_HISTORY` | Get Organization Billing History | Retrieve the organization's billing history from eSputnik, broken down by day and media channel. Use this tool to: - View costs per messaging channel (email, SMS, Viber, push notifications, etc.) - Track message volumes and spending over time - Analyze bonus credits usage and fund withdrawals - Generate billing reports for specific date ranges Returns daily breakdowns including messages sent, funds spent, and bonuses used per channel. |
| `ESPUTNIK_GET_PREPROCESSOR_FILE_STATUS` | Get Preprocessor File Status | Retrieve the status of a preprocessor file upload session. Use this tool to poll for the asynchronous processing status of a previously submitted preprocessor file. The ID parameter is the asyncSessionId returned by the 'Upload file for preprocessor' endpoint. Common status values: PENDING, PROCESSING, COMPLETED, ERROR. |
| `ESPUTNIK_GET_PRODUCT_FEEDS` | Get Product Feeds Configuration | Tool to retrieve product feeds configuration from eSputnik. Use when you need to check current product feed settings including feed type, update frequency, and other configuration parameters. This is a read-only operation that returns the complete product feeds configuration. |
| `ESPUTNIK_GET_PROMOCODES_COUNT` | Get Promocodes Count | Get the number of available promotional codes in eSputnik. Use this action to check how many promo codes are available, optionally filtering by type, active due days, or discount amount. |
| `ESPUTNIK_GET_SITE_DOMAIN` | Get Site Domain | Retrieve the organization's domain configuration from eSputnik. Use this tool to check the configured domain for your organization, which is used for web tracking, widgets, and web push notifications. The response will be empty if no domain has been configured for your account. Returns domain details including the domain name, internal identifier, and status. No parameters required - uses the authenticated account credentials automatically. This is a read-only, idempotent operation that can be called multiple times safely. |
| `ESPUTNIK_GET_SITE_SCRIPT` | Get Site Tracking Script | Retrieve the site tracking script for your eSputnik account. Use this tool to obtain the tracking script code that can be embedded on websites to enable eSputnik tracking and functionality. The domain must be configured in your organization before requesting the script. This is particularly useful for plugins that automatically install scripts and need programmatic access to the tracking code. Returns the complete tracking script as plain text ready for website integration. No parameters required - uses the authenticated account credentials automatically. This is a read-only, idempotent operation that can be called multiple times safely. |
| `ESPUTNIK_GET_SMS_INTERFACES` | Get SMS Interfaces | Retrieve all SMS interfaces (alpha names) configured for the organization. Use this tool to get the list of available SMS sender identifiers (alpha names) that can be used when sending SMS messages through eSputnik. Alpha names are pre-configured sender IDs that recipients see as the message sender. This is useful when: - You need to select a specific sender ID for SMS campaigns - You want to list all available SMS sending options - You need to verify which alpha names are configured and active No parameters required - returns all SMS interfaces for the authenticated account. |
| `ESPUTNIK_GET_SUBSCRIPTION_CATEGORIES` | Get Subscription Categories | Retrieve all subscription categories for the organization. This action returns the complete list of subscription categories (communication types) configured in your eSputnik account. Subscription categories typically represent different types of communications like newsletters, promotions, transactional emails, etc. Use this action when you need to: - List all available subscription types in your eSputnik account - Get category IDs and keys for use in other API calls - Understand the structure of subscription options available to contacts - Build subscription management interfaces Returns an empty array if no subscription categories are configured. This is a read-only, idempotent operation that can be called multiple times safely. |
| `ESPUTNIK_GET_TELEGRAM_MESSAGE` | Get Telegram Message | Retrieve a Telegram bot message by its unique identifier from eSputnik. Use this tool to fetch Telegram bot message content, configuration, and metadata before sending, editing, or reviewing a notification. Returns complete message details including text, formatting, keyboard markup, and notification settings. Rate limit: 500 requests per hour. |
| `ESPUTNIK_LIST_PROMOCODES` | List Promotional Codes | Retrieve a list of promotional codes from eSputnik. Use this tool to view all available promo codes, filter by type, usage status, expiration, or discount value. Useful for campaign planning and promo code management. |
| `ESPUTNIK_LIST_WEBPUSH_DOMAINS` | List Web Push Domains | Retrieve the list of domains registered for web push notifications. Use this tool to get all domains configured in your eSputnik account for web push notification functionality. This is useful for verifying domain registration status and managing web push notification configurations. Returns a list of domain names that have been registered. No parameters required - uses the authenticated account credentials automatically. This is a read-only, idempotent operation that can be called multiple times safely. |
| `ESPUTNIK_REMOVE_FROM_UNSUBSCRIBED` | Remove From Unsubscribed | Tool to remove email addresses from the unsubscribed contacts list in eSputnik. Use when you need to re-enable email addresses that were previously unsubscribed. |
| `ESPUTNIK_SEARCH_APP_INBOX_MESSAGES` | Search App Inbox Messages | Search for mobile App Inbox messages using a part of the name or a tag. Returns a maximum of 500 messages per request with pagination support. Use this tool to find App Inbox messages by name or tag, list all available messages, or navigate through large message lists using pagination. The TotalCount header indicates the number of messages returned by the search query. |
| `ESPUTNIK_SEARCH_CONTACTS` | Search Contacts | Search for all contacts in a segment (group). Use this action to: - Retrieve contacts from a specific segment by segment ID - Paginate through large contact lists using startindex and maxrows - Sort contacts by addition time to the segment or by default order - Export contact lists from segments for analysis or sync purposes The API returns a list of contact objects with their channels, names, addresses, and custom fields. Results can be paginated using startindex and maxrows parameters. Maximum 500 contacts per request. |
| `ESPUTNIK_SEARCH_EMAIL_MESSAGES` | Search Email Messages | Search for email messages using a part of their name or a tag. Use this tool to: - Find email messages by name or tag - List all available email message templates - Navigate through messages using pagination (startindex + maxrows) The method returns a maximum of 500 messages per request. The TotalCount header contains the total number of messages returned to the query. By default, a rate limit of 500 requests per hour applies. |
| `ESPUTNIK_SEARCH_MOBILEPUSH_MESSAGES` | Search Mobile Push Messages | Search for mobile push messages using part of the name or a tag. Use this tool to: - Find mobile push messages by searching for keywords in message names - Filter messages by tags assigned to them - Retrieve all mobile push messages when no search criteria provided - Navigate through large result sets using pagination (startindex + maxrows) Returns up to 500 messages per request. The TotalCount header indicates the total number of messages matching your query. Rate limit: 500 requests per hour. |
| `ESPUTNIK_SEARCH_SEGMENTS` | Search Segments | Search for and retrieve available segments (groups) in eSputnik. Use this action to: - List all segments/groups in your eSputnik account - Search for segments by name (supports partial matching) - Paginate through large segment lists using startindex and maxrows - Get segment IDs for use in other API calls (e.g., adding contacts to segments) Segments are groups of contacts that can be static (manually managed), dynamic (rule-based), or combined (mix of both). The API returns segment details including ID, name, and type. Maximum 500 segments per request. |
| `ESPUTNIK_SEARCH_SMS_MESSAGES` | Search SMS Messages | Search for SMS messages using part of their names or tags in eSputnik. Use this tool to find SMS message templates by searching through message names or associated tags. Returns up to 500 messages per request with pagination support. The API returns the total count of matching messages in the TotalCount response header. Rate limit: 500 requests per hour by default. |
| `ESPUTNIK_SEARCH_TELEGRAM_MESSAGES` | Search Telegram Messages | Search for Telegram bot messages using a part of name or a tag. Use this tool to: - Find Telegram bot messages by name or tag - List all Telegram bot messages in the account - Navigate through messages using pagination (startindex + maxrows) Returns message details including IDs, names, tags, and status information. Results are paginated - use startindex and maxrows to navigate through large lists. A maximum of 500 messages can be returned per request. The TotalCount header contains the total number of messages matching the query. Rate limit: 500 requests per hour by default. |
| `ESPUTNIK_SEARCH_VIBER_MESSAGES` | Search Viber Messages | Search for Viber messages using part of the name or a tag. Use this tool to: - Find Viber messages by searching for keywords in message names - Filter messages by tags assigned to them - Retrieve all Viber messages when no search criteria provided - Navigate through large result sets using pagination (startindex + maxrows) Returns up to 500 messages per request. The TotalCount header indicates the total number of messages matching your query. Rate limit: 500 requests per hour. |
| `ESPUTNIK_SEARCH_WORKFLOWS` | Search Workflows | Search for and retrieve available workflows from eSputnik. Use this tool to list all workflows in your eSputnik account, with optional filtering by workflow name. Returns workflow details including IDs, names, statuses, and timestamps. Results are paginated - use startindex and maxrows to navigate through large lists. |
| `ESPUTNIK_SEND_EMAIL` | Send Email | Send an email message to one or more contacts via eSputnik API. Use this action to send transactional or marketing emails. If no contact exists with the recipient email address, a new contact will be automatically created. Supports HTML content, plain text fallback, AMP emails, and URL tracking. Prerequisites: - Valid eSputnik API credentials - Verified sender email address in your eSputnik account - At least one recipient email address Example: "Send welcome email to new@user.com with subject 'Welcome' and HTML content" |
| `ESPUTNIK_SEND_PREPARED_MESSAGE` | Send Prepared Message | Tool to send a prepared message to one or many contacts. Use when you need to send broadcasts for Email, SMS, Mobile Push, Web Push, Viber, or Telegram bot channels using pre-created message templates. The method allows sending to up to 1,000 recipients in a single request. You can parametrize the message for each contact individually using jsonParam field for personalization. Recipients can be identified by contactId (eSputnik internal ID) or locator (email/phone). |
| `ESPUTNIK_SUBSCRIBE_CONTACT` | Subscribe Contact | Tool to subscribe a contact for double opt-in implementation. Use when integrating subscription forms on your website or app. This method is designed for double opt-in implementation: - If a contact does not exist, it is created with a non-confirmed email status - If a contact exists, the contact fields are updated (except existing media channels) - New contacts are created with a not confirmed status and cannot receive bulk emails until they confirm their subscription - However, unconfirmed contacts are available for receiving important trigger messages - An event is automatically generated after this method is called, which can be used to send confirmation emails via campaigns - When clicking the confirmation link, a contact becomes confirmed and available for bulk emails Note: This differs from bulk contact import - contacts created here are unconfirmed by default. |
| `ESPUTNIK_UPDATE_APP_INBOX_MESSAGE` | Update App Inbox Message | Tool to update the base App Inbox message in eSputnik. Use when you need to modify message content, title, link, or settings. This method updates an existing App Inbox message by its ID. All required fields (name, title, text) must be provided even if unchanged. Optional fields like link, image, and TTL can be updated as needed. |
| `ESPUTNIK_UPDATE_APPINBOX_TRANSLATION` | Update App Inbox Translation | Tool to update or add a language version for an App Inbox message in eSputnik. Use when you need to add multilingual support or update existing translations for App Inbox notifications. This action allows updating the title, text, link, image, and other properties for a specific language version of an App Inbox message. If the language version doesn't exist, it will be created; if it exists, it will be updated with the new content. |
| `ESPUTNIK_UPDATE_CONTACT` | Update Contact | Tool to update contact information by contact ID. Use when you need to modify an existing contact's details. This action updates an existing contact identified by their eSputnik contact ID. You can update any combination of contact fields including name, channels, address, and custom fields. Only the fields you provide will be updated; other fields remain unchanged. |
| `ESPUTNIK_UPDATE_CONTACT_SUBSCRIPTIONS` | Update Contact Subscriptions | Tool to update the subscription categories a contact is enrolled in. Use when you need to modify which communication types a contact receives. This action replaces the contact's current subscription list with the provided categories. Pass an empty array to unsubscribe from all categories. Returns success if the contact exists. |
| `ESPUTNIK_UPDATE_EMAIL_MESSAGE` | Update Email Message | Tool to update an existing email message in eSputnik. Use when you need to modify the content, subject, sender, or other properties of an existing email template. This action updates the basic email message properties including HTML content, subject line, sender information, and optional fields like AMP HTML, CSS styles, and subscription categories. The 'languageCode' parameter allows updating specific language versions for multilingual campaigns. |
| `ESPUTNIK_UPDATE_EMAIL_TRANSLATION` | Update Email Translation | Tool to update or add a language version for a base email message in eSputnik. Use when you need to add multilingual support to an existing email template or update an existing translation. This action updates the translation for a specific language of an existing email message. If the translation for the specified language doesn't exist, it will be created. The base message must already exist in eSputnik. |
| `ESPUTNIK_UPDATE_INTERACTION_STATUS` | Update Interaction Status | Tool to update the status of a message interaction using interaction_id. Use when you need to report message delivery, open, click, or undelivery events. The interaction_id is sent along with message data (e.g., in Mobile Push as 'es_interaction_id'). This action allows you to report back to eSputnik when a message is delivered, opened, clicked, or fails to deliver, enabling accurate tracking and analytics. |
| `ESPUTNIK_UPDATE_MOBILEPUSH_MESSAGE` | Update Mobile Push Message | Tool to update an existing mobile push notification message in eSputnik. Use when you need to modify a previously created push notification campaign. Updates message content including title, body text, images, action buttons, and custom data. Supports multilingual messages through the translations field. Requires the message ID and all required fields (name, title, text) must be provided even if not changing. |
| `ESPUTNIK_UPDATE_MOBILEPUSH_TRANSLATION` | Update Mobile Push Translation | Tool to update or add a language version for a mobile push message in eSputnik. Use when you need to create or modify translations for multilingual push notification campaigns. This action allows you to manage language-specific versions of a base mobile push message, enabling targeted communication with users in their preferred language. The translation can include localized title, text, images, buttons, and other notification settings. |
| `ESPUTNIK_UPDATE_PREPROCESSOR_FILE_BY_ID` | Update Preprocessor File By ID | Tool to update a preprocessor file's data by providing a new external link. Use when you need to refresh or change the data source for an already uploaded preprocessor file. The file ID must be obtained from a previous Upload file for preprocessor operation. This method updates the file metadata including the external data link and time-to-live. |
| `ESPUTNIK_UPDATE_SMS_MESSAGE` | Update SMS Message | Tool to update an existing base SMS message template in eSputnik. Use when you need to modify the sender name, message text, or other properties of an existing SMS template. The SMS message must already exist with the provided ID. All three required fields (from, name, text) must be provided even if only updating some properties. The action supports multilingual messages through the languageCode parameter. |
| `ESPUTNIK_UPDATE_SMS_TRANSLATION` | Update SMS Translation | Tool to update a language version of an SMS message in eSputnik. Use when you need to modify the content, sender name, or other properties of a specific language translation of an SMS message. This action updates an existing translation while keeping other language versions intact. The SMS message must already exist, and you're updating the specified language version. |
| `ESPUTNIK_UPDATE_TELEGRAM_MESSAGE` | Update Telegram Message | Update a base Telegram bot message in eSputnik. Use when you need to modify an existing message template's content, buttons, or metadata. The message template is updated in eSputnik and can later be sent to contacts using the Send Message API. Only the fields provided in the request will be updated. Prerequisites: - Valid eSputnik API credentials with write permissions - Telegram bot configured in your eSputnik account - Valid message ID for an existing Telegram message Example usage: "Update Telegram message 4404257 with new text 'Updated content'" |
| `ESPUTNIK_UPDATE_TELEGRAM_TRANSLATION` | Update Telegram Translation | Update a translated telegram bot message in eSputnik. Use when you need to modify an existing translation of a Telegram bot message. This action allows you to update the content, buttons, image, and metadata of a specific language version of a Telegram bot message. The message must already exist in eSputnik, and you must specify both the message ID and the language code to update. |
| `ESPUTNIK_UPLOAD_PREPROCESSOR_FILE` | Upload Preprocessor File | Tool to upload a file for the preprocessor from an external repository. Use when you need to import preprocessor data from an external URL. The file is uploaded asynchronously - this endpoint returns immediately with a session ID that can be used to poll for completion status using the GetPreprocessorFileStatus action. The file will remain in the system for the specified TTL period (default: 1 month). |
| `ESPUTNIK_UPLOAD_PROMOCODES` | Upload Promotional Codes | Tool to upload promotional codes to eSputnik in bulk. Use this action to create new promo codes or update existing ones. Existing promotional codes with the same string value will be updated with the new discount, expiration date, type, and usage status. |

## Supported Triggers

None listed.

## Creating MCP Server - Stand-alone vs Composio SDK

The Esputnik MCP server is an implementation of the Model Context Protocol that connects your AI agent to Esputnik. It provides structured and secure access so your agent can perform Esputnik operations on your behalf through a secure, permission-based interface.
With Composio's managed implementation, you don't have to create your own developer app. For production, if you're building an end product, we recommend using your own credentials. The managed server helps you prototype fast and go from 0-1 faster.

## Step-by-step Guide

### 1. Prerequisites

Before starting, make sure you have:
- Composio API Key and OpenAI API Key
- Primary know-how of OpenAI Agents SDK
- A live Esputnik project
- Some knowledge of Python or Typescript

### 1. Getting API Keys for OpenAI and Composio

OpenAI API Key
- Go to the [OpenAI dashboard](https://platform.openai.com/settings/organization/api-keys) and create an API key. You'll need credits to use the models, or you can connect to another model provider.
- Keep the API key safe.
Composio API Key
- Log in to the [Composio dashboard](https://dashboard.composio.dev?utm_source=toolkits&utm_medium=framework_docs).
- Go to Settings and copy your API key.

### 2. Install dependencies

Install the Composio SDK and the OpenAI Agents SDK.
```python
pip install composio_openai_agents openai-agents python-dotenv
```

```typescript
npm install @composio/openai-agents @openai/agents dotenv
```

### 3. Set up environment variables

Create a .env file and add your OpenAI and Composio API keys.
```bash
OPENAI_API_KEY=sk-...your-api-key
COMPOSIO_API_KEY=your-api-key
USER_ID=composio_user@gmail.com
```

### 4. Import dependencies

What's happening:
- You're importing all necessary libraries.
- The Composio and OpenAIAgentsProvider classes are imported to connect your OpenAI agent to Composio tools like Esputnik.
```python
import asyncio
import os
from dotenv import load_dotenv

from composio import Composio
from composio_openai_agents import OpenAIAgentsProvider
from agents import Agent, Runner, HostedMCPTool, SQLiteSession
```

```typescript
import 'dotenv/config';
import { Composio } from '@composio/core';
import { OpenAIAgentsProvider } from '@composio/openai-agents';
import { Agent, hostedMcpTool, run, OpenAIConversationsSession } from '@openai/agents';
import * as readline from 'readline';
```

### 5. Set up the Composio instance

No description provided.
```python
load_dotenv()

api_key = os.getenv("COMPOSIO_API_KEY")
user_id = os.getenv("USER_ID")

if not api_key:
    raise RuntimeError("COMPOSIO_API_KEY is not set. Create a .env file with COMPOSIO_API_KEY=your_key")

# Initialize Composio
composio = Composio(api_key=api_key, provider=OpenAIAgentsProvider())
```

```typescript
dotenv.config();

const composioApiKey = process.env.COMPOSIO_API_KEY;
const userId = process.env.USER_ID;

if (!composioApiKey) {
  throw new Error('COMPOSIO_API_KEY is not set. Create a .env file with COMPOSIO_API_KEY=your_key');
}
if (!userId) {
  throw new Error('USER_ID is not set');
}

// Initialize Composio
const composio = new Composio({
  apiKey: composioApiKey,
  provider: new OpenAIAgentsProvider(),
});
```

### 6. Create a Tool Router session

What is happening:
- You give the Tool Router the user id and the toolkits you want available. Here, it is only esputnik.
- The router checks the user's Esputnik connection and prepares the MCP endpoint.
- The returned session.mcp.url is the MCP URL that your agent will use to access Esputnik.
- This approach keeps things lightweight and lets the agent request Esputnik tools only when needed during the conversation.
```python
# Create a Esputnik Tool Router session
session = composio.create(
    user_id=user_id,
    toolkits=["esputnik"]
)

mcp_url = session.mcp.url
```

```typescript
// Create Tool Router session for Esputnik
const session = await composio.create(userId as string, {
  toolkits: ['esputnik'],
});
const mcpUrl = session.mcp.url;
```

### 7. Configure the agent

No description provided.
```python
# Configure agent with MCP tool
agent = Agent(
    name="Assistant",
    model="gpt-5",
    instructions=(
        "You are a helpful assistant that can access Esputnik. "
        "Help users perform Esputnik operations through natural language."
    ),
    tools=[
        HostedMCPTool(
            tool_config={
                "type": "mcp",
                "server_label": "tool_router",
                "server_url": mcp_url,
                "headers": {"x-api-key": api_key},
                "require_approval": "never",
            }
        )
    ],
)
```

```typescript
// Configure agent with MCP tool
const agent = new Agent({
  name: 'Assistant',
  model: 'gpt-5',
  instructions:
    'You are a helpful assistant that can access Esputnik. Help users perform Esputnik operations through natural language.',
  tools: [
    hostedMcpTool({
      serverLabel: 'tool_router',
      serverUrl: mcpUrl,
      headers: { 'x-api-key': composioApiKey },
      requireApproval: 'never',
    }),
  ],
});
```

### 8. Start chat loop and handle conversation

No description provided.
```python
print("\nComposio Tool Router session created.")

chat_session = SQLiteSession("conversation_openai_toolrouter")

print("\nChat started. Type your requests below.")
print("Commands: 'exit', 'quit', or 'q' to end\n")

async def main():
    try:
        result = await Runner.run(
            agent,
            "What can you help me with?",
            session=chat_session
        )
        print(f"Assistant: {result.final_output}\n")
    except Exception as e:
        print(f"Error: {e}\n")

    while True:
        user_input = input("You: ").strip()
        if user_input.lower() in {"exit", "quit", "q"}:
            print("Goodbye!")
            break

        result = await Runner.run(
            agent,
            user_input,
            session=chat_session
        )
        print(f"Assistant: {result.final_output}\n")

asyncio.run(main())
```

```typescript
// Keep conversation state across turns
const conversationSession = new OpenAIConversationsSession();

// Simple CLI
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
  prompt: 'You: ',
});

console.log('\nComposio Tool Router session created.');
console.log('\nChat started. Type your requests below.');
console.log("Commands: 'exit', 'quit', or 'q' to end\n");

try {
  const first = await run(agent, 'What can you help me with?', { session: conversationSession });
  console.log(`Assistant: ${first.finalOutput}\n`);
} catch (e) {
  console.error('Error:', e instanceof Error ? e.message : e, '\n');
}

rl.prompt();

rl.on('line', async (userInput) => {
  const text = userInput.trim();

  if (['exit', 'quit', 'q'].includes(text.toLowerCase())) {
    console.log('Goodbye!');
    rl.close();
    process.exit(0);
  }

  if (!text) {
    rl.prompt();
    return;
  }

  try {
    const result = await run(agent, text, { session: conversationSession });
    console.log(`\nAssistant: ${result.finalOutput}\n`);
  } catch (e) {
    console.error('Error:', e instanceof Error ? e.message : e, '\n');
  }

  rl.prompt();
});

rl.on('close', () => {
  console.log('\n👋 Session ended.');
  process.exit(0);
});
```

## Complete Code

```python
import asyncio
import os
from dotenv import load_dotenv

from composio import Composio
from composio_openai_agents import OpenAIAgentsProvider
from agents import Agent, Runner, HostedMCPTool, SQLiteSession

load_dotenv()

api_key = os.getenv("COMPOSIO_API_KEY")
user_id = os.getenv("USER_ID")

if not api_key:
    raise RuntimeError("COMPOSIO_API_KEY is not set. Create a .env file with COMPOSIO_API_KEY=your_key")

# Initialize Composio
composio = Composio(api_key=api_key, provider=OpenAIAgentsProvider())

# Create Tool Router session
session = composio.create(
    user_id=user_id,
    toolkits=["esputnik"]
)
mcp_url = session.mcp.url

# Configure agent with MCP tool
agent = Agent(
    name="Assistant",
    model="gpt-5",
    instructions=(
        "You are a helpful assistant that can access Esputnik. "
        "Help users perform Esputnik operations through natural language."
    ),
    tools=[
        HostedMCPTool(
            tool_config={
                "type": "mcp",
                "server_label": "tool_router",
                "server_url": mcp_url,
                "headers": {"x-api-key": api_key},
                "require_approval": "never",
            }
        )
    ],
)

print("\nComposio Tool Router session created.")

chat_session = SQLiteSession("conversation_openai_toolrouter")

print("\nChat started. Type your requests below.")
print("Commands: 'exit', 'quit', or 'q' to end\n")

async def main():
    try:
        result = await Runner.run(
            agent,
            "What can you help me with?",
            session=chat_session
        )
        print(f"Assistant: {result.final_output}\n")
    except Exception as e:
        print(f"Error: {e}\n")

    while True:
        user_input = input("You: ").strip()
        if user_input.lower() in {"exit", "quit", "q"}:
            print("Goodbye!")
            break

        result = await Runner.run(
            agent,
            user_input,
            session=chat_session
        )
        print(f"Assistant: {result.final_output}\n")

asyncio.run(main())
```

```typescript
import 'dotenv/config';
import { Composio } from '@composio/core';
import { OpenAIAgentsProvider } from '@composio/openai-agents';
import { Agent, hostedMcpTool, run, OpenAIConversationsSession } from '@openai/agents';
import * as readline from 'readline';

const composioApiKey = process.env.COMPOSIO_API_KEY;
const userId = process.env.USER_ID;

if (!composioApiKey) {
  throw new Error('COMPOSIO_API_KEY is not set. Create a .env file with COMPOSIO_API_KEY=your_key');
}
if (!userId) {
  throw new Error('USER_ID is not set');
}

// Initialize Composio
const composio = new Composio({
  apiKey: composioApiKey,
  provider: new OpenAIAgentsProvider(),
});

async function main() {
  // Create Tool Router session
  const session = await composio.create(userId as string, {
    toolkits: ['esputnik'],
  });
  const mcpUrl = session.mcp.url;

  // Configure agent with MCP tool
  const agent = new Agent({
    name: 'Assistant',
    model: 'gpt-5',
    instructions:
      'You are a helpful assistant that can access Esputnik. Help users perform Esputnik operations through natural language.',
    tools: [
      hostedMcpTool({
        serverLabel: 'tool_router',
        serverUrl: mcpUrl,
        headers: { 'x-api-key': composioApiKey },
        requireApproval: 'never',
      }),
    ],
  });

  // Keep conversation state across turns
  const conversationSession = new OpenAIConversationsSession();

  // Simple CLI
  const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout,
    prompt: 'You: ',
  });

  console.log('\nComposio Tool Router session created.');
  console.log('\nChat started. Type your requests below.');
  console.log("Commands: 'exit', 'quit', or 'q' to end\n");

  try {
    const first = await run(agent, 'What can you help me with?', { session: conversationSession });
    console.log(`Assistant: ${first.finalOutput}\n`);
  } catch (e) {
    console.error('Error:', e instanceof Error ? e.message : e, '\n');
  }

  rl.prompt();

  rl.on('line', async (userInput) => {
    const text = userInput.trim();

    if (['exit', 'quit', 'q'].includes(text.toLowerCase())) {
      console.log('Goodbye!');
      rl.close();
      process.exit(0);
    }

    if (!text) {
      rl.prompt();
      return;
    }

    try {
      const result = await run(agent, text, { session: conversationSession });
      console.log(`\nAssistant: ${result.finalOutput}\n`);
    } catch (e) {
      console.error('Error:', e instanceof Error ? e.message : e, '\n');
    }

    rl.prompt();
  });

  rl.on('close', () => {
    console.log('\nSession ended.');
    process.exit(0);
  });
}

main().catch((err) => {
  console.error('Fatal error:', err);
  process.exit(1);
});
```

## Conclusion

This was a starter code for integrating Esputnik MCP with OpenAI Agents SDK to build a functional AI agent that can interact with Esputnik.
Key features:
- Hosted MCP tool integration through Composio's Tool Router
- SQLite session persistence for conversation history
- Simple async chat loop for interactive testing
You can extend this by adding more toolkits, implementing custom business logic, or building a web interface around the agent.

## How to build Esputnik MCP Agent with another framework

- [Claude Agent SDK](https://composio.dev/toolkits/esputnik/framework/claude-agents-sdk)
- [Claude Code](https://composio.dev/toolkits/esputnik/framework/claude-code)
- [Claude Cowork](https://composio.dev/toolkits/esputnik/framework/claude-cowork)
- [Codex](https://composio.dev/toolkits/esputnik/framework/codex)
- [OpenClaw](https://composio.dev/toolkits/esputnik/framework/openclaw)
- [Hermes](https://composio.dev/toolkits/esputnik/framework/hermes-agent)
- [CLI](https://composio.dev/toolkits/esputnik/framework/cli)
- [Google ADK](https://composio.dev/toolkits/esputnik/framework/google-adk)
- [LangChain](https://composio.dev/toolkits/esputnik/framework/langchain)
- [Vercel AI SDK](https://composio.dev/toolkits/esputnik/framework/ai-sdk)
- [Mastra AI](https://composio.dev/toolkits/esputnik/framework/mastra-ai)
- [LlamaIndex](https://composio.dev/toolkits/esputnik/framework/llama-index)
- [CrewAI](https://composio.dev/toolkits/esputnik/framework/crew-ai)

## Related Toolkits

- [Reddit](https://composio.dev/toolkits/reddit) - Reddit is a social news platform with thriving user-driven communities (subreddits). It's the go-to place for discussion, content sharing, and viral marketing.
- [Facebook](https://composio.dev/toolkits/facebook) - Facebook is a social media and advertising platform for businesses and creators. It helps you connect, share, and manage content across your public Facebook Pages.
- [Linkedin](https://composio.dev/toolkits/linkedin) - LinkedIn is a professional networking platform for connecting, sharing content, and engaging with business opportunities. It's the go-to place for building your professional brand and unlocking new career connections.
- [Active campaign](https://composio.dev/toolkits/active_campaign) - ActiveCampaign is a marketing automation and CRM platform for managing email campaigns, sales pipelines, and customer segmentation. It helps businesses engage customers and drive growth through smart automation and targeted outreach.
- [ActiveTrail](https://composio.dev/toolkits/active_trail) - ActiveTrail is a user-friendly email marketing and automation platform. It helps you reach subscribers and automate campaigns with ease.
- [Ahrefs](https://composio.dev/toolkits/ahrefs) - Ahrefs is an SEO and marketing platform for site audits, keyword research, and competitor insights. It helps you improve search rankings and drive organic traffic.
- [Amcards](https://composio.dev/toolkits/amcards) - AMCards lets you create and mail personalized greeting cards online. Build stronger customer relationships with easy, automated card campaigns.
- [Beamer](https://composio.dev/toolkits/beamer) - Beamer is a news and changelog platform for in-app announcements and feature updates. It helps companies boost user engagement by sharing news where users are most active.
- [Benchmark email](https://composio.dev/toolkits/benchmark_email) - Benchmark Email is a platform for creating, sending, and tracking email campaigns. It's built to help you engage audiences and analyze results—all in one place.
- [Bigmailer](https://composio.dev/toolkits/bigmailer) - BigMailer is an email marketing platform for managing multiple brands with white-labeling and automation. It helps teams streamline campaigns and simplify integration with Amazon SES.
- [Brandfetch](https://composio.dev/toolkits/brandfetch) - Brandfetch is an API that delivers company logos, colors, and visual branding assets. It helps marketers and developers keep brand visuals consistent everywhere.
- [Brevo](https://composio.dev/toolkits/brevo) - Brevo is an all-in-one email and SMS marketing platform for transactional messaging, automation, and CRM. It helps businesses engage customers and streamline communications through powerful campaign tools.
- [Campayn](https://composio.dev/toolkits/campayn) - Campayn is an email marketing platform for creating, sending, and managing campaigns. It helps businesses engage contacts and grow audiences with easy-to-use tools.
- [Cardly](https://composio.dev/toolkits/cardly) - Cardly is a platform for creating and sending personalized direct mail to customers. It helps businesses break through the digital clutter by getting real engagement via physical mailboxes.
- [ClickSend](https://composio.dev/toolkits/clicksend) - ClickSend is a cloud-based SMS and email marketing platform for businesses. It streamlines communication by enabling quick message delivery and contact management.
- [Crustdata](https://composio.dev/toolkits/crustdata) - CrustData is an AI-powered data intelligence platform for real-time company and people data. It helps B2B sales teams, AI SDRs, and investors react to live business signals.
- [Curated](https://composio.dev/toolkits/curated) - Curated is a platform for collecting, curating, and publishing newsletters. It streamlines content aggregation and distribution for creators and teams.
- [Customerio](https://composio.dev/toolkits/customerio) - Customer.io is a customer engagement platform for targeted messaging across email, SMS, and push. Easily automate, segment, and track communications with your audience.
- [Cutt ly](https://composio.dev/toolkits/cutt_ly) - Cutt.ly is a URL shortening service for managing and analyzing links. Streamline your workflows with quick, trackable, and branded short URLs.
- [Demio](https://composio.dev/toolkits/demio) - Demio is webinar software built for marketers, offering both live and automated sessions with interactive features. It helps teams engage audiences and optimize lead generation through detailed analytics.

## Frequently Asked Questions

### What are the differences in Tool Router MCP and Esputnik MCP?

With a standalone Esputnik MCP server, the agents and LLMs can only access a fixed set of Esputnik tools tied to that server. However, with the Composio Tool Router, agents can dynamically load tools from Esputnik and many other apps based on the task at hand, all through a single MCP endpoint.

### Can I use Tool Router MCP with OpenAI Agents SDK?

Yes, you can. OpenAI Agents SDK fully supports MCP integration. You get structured tool calling, message history handling, and model orchestration while Tool Router takes care of discovering and serving the right Esputnik tools.

### Can I manage the permissions and scopes for Esputnik while using Tool Router?

Yes, absolutely. You can configure which Esputnik scopes and actions are allowed when connecting your account to Composio. You can also bring your own OAuth credentials or API configuration so you keep full control over what the agent can do.

### How safe is my data with Composio Tool Router?

All sensitive data such as tokens, keys, and configuration is fully encrypted at rest and in transit. Composio is SOC 2 Type 2 compliant and follows strict security practices so your Esputnik data and credentials are handled as safely as possible.

---
[See all toolkits](https://composio.dev/toolkits) · [Composio docs](https://docs.composio.dev/llms.txt)
