Back to Developer

MCP Platform Guide

Deep dive into the Model Context Protocol integration. Transport modes, the complete tool reference, custom tools, execution auditing, approval workflows, and authentication.

Transport Modes

The WhaleTools MCP server supports two transport modes. Choose based on your client environment.

stdio Transport

The default mode for CLI-based clients like Claude Desktop and Cursor. The MCP server runs as a child process, communicating over stdin/stdout with JSON-RPC messages. No network configuration required.

claude_desktop_config.json
{
"mcpServers": {
"whaletools": {
"command": "npx",
"args": ["-y", "whale-code", "mcp", "--store", "your-store-id"],
"env": {
"WHALETOOLS_API_KEY": "wt_live_..."
}
}
}
}

The server starts on demand when the client connects and exits when the client disconnects. All tool calls are serialized over the stdio pipe.

HTTP/SSE Transport

For web-based clients, remote connections, and multi-tenant setups. The MCP server runs as a persistent HTTP service, accepting connections via Server-Sent Events for real-time streaming.

bash
# Start the MCP server in HTTP/SSE mode
npx whale-code mcp --transport sse --port 3100 --store your-store-id
# The server exposes two endpoints:
# GET /sse — SSE connection endpoint
# POST /messages — JSON-RPC message endpoint

Connect from any HTTP client by opening an SSE stream and posting JSON-RPC messages:

client.ts
// Connect to the SSE endpoint
const eventSource = new EventSource(
"http://localhost:3100/sse",
{ headers: { "Authorization": "Bearer wt_live_..." } }
);
eventSource.onmessage = (event) => {
const response = JSON.parse(event.data);
console.log("Tool result:", response);
};
// Send a tool call via POST
await fetch("http://localhost:3100/messages", {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": "Bearer wt_live_..."
},
body: JSON.stringify({
jsonrpc: "2.0",
id: 1,
method: "tools/call",
params: {
name: "products_list_products",
arguments: { limit: 10, status: "active" }
}
})
});

When to use each transport

stdio — Local development, Claude Desktop, Cursor, single-user CLI tools. Zero setup.

HTTP/SSE — Web apps, shared servers, multi-tenant deployments, or when the client cannot spawn subprocesses.

Complete Tool Reference

52 tools organized across 6 categories. Each tool exposes multiple actions that map to WhaleTools API endpoints.

Commerce 12Intelligence 6Marketing 10Content 5Platform 15Operations 4

Commerce12 tools

products

products

Manage product catalog: create, update, list, search, and delete products with variants and pricing.

list_productsget_productcreate_productupdate_productdelete_product

orders

orders

Full order lifecycle management including creation, status updates, refunds, and fulfillment.

list_ordersget_ordercreate_orderupdate_ordercancel_order

customers

customers

Customer records, profiles, segmentation, and purchase history lookups.

list_customersget_customercreate_customerupdate_customerenrich_customer

inventory

inventory

Stock levels, adjustments, transfers between locations, and low-stock alerts.

list_inventoryget_inventoryadjust_stocktransfer_stock

collections

catalog

Create and manage product collections and automated smart collections.

list_collectionscreate_collectionadd_products

loyalty

commerce

Manage loyalty programs, point balances, rewards, and tier rules.

get_balanceadd_pointsredeemlist_rewards

coupons

commerce

Create and manage discount coupons, promo codes, and usage limits.

list_couponscreate_couponvalidatedeactivate

fulfillment

orders

Manage fulfillment workflows, shipments, tracking, and delivery status.

create_fulfillmentupdate_trackingget_status

reviews

catalog

Product reviews, ratings, moderation, and response management.

list_reviewsapproverespondget_summary

tax

commerce

Tax rate configuration, calculation, and reporting by jurisdiction.

calculate_taxlist_ratesget_report

invoices

commerce

Create, send, and track invoices with payment status and reminders.

list_invoicescreate_invoicesendmark_paid

wholesale

commerce

Wholesale pricing, bulk orders, and B2B customer management.

list_pricesset_pricingcreate_bulk_order

Intelligence6 tools

analytics

analytics

Sales reports, customer metrics, inventory turnover, and revenue dashboards.

sales_reportinventory_reportcustomer_report

web_search

platform

Search the web for competitor data, market research, and product information.

searchfetch_pageextract_data

discovery

catalog

Product recommendations, related items, and personalized discovery feeds.

get_recommendationssimilar_productstrending

enrichment

platform

Enrich product and customer data with external sources and AI analysis.

enrich_productenrich_customerbulk_enrich

embeddings

platform

Generate and query vector embeddings for semantic search and similarity.

create_embeddingquery_similarindex_catalog

llm

ai

Direct access to language model inference for custom prompts and analysis.

generateclassifysummarizeextract

Marketing10 tools

email

marketing

Send transactional and marketing emails using templates or custom content.

send_emaillist_templatesrender_template

voice

phone

Initiate and manage voice calls, play prompts, and record conversations.

make_calllist_callsget_recording

meta_ads

marketing

Manage Meta (Facebook/Instagram) ad campaigns, audiences, and performance.

list_campaignscreate_campaignget_metrics

google_ads

marketing

Manage Google Ads campaigns, keywords, and bidding strategies.

list_campaignscreate_campaignget_metrics

segments

customers

Build and query customer segments based on behavior and attributes.

list_segmentscreate_segmentget_members

campaigns

marketing

Create and manage marketing campaigns across email, SMS, and ads.

list_campaignscreate_campaignget_metricspause

affiliates

commerce

Affiliate program management, referral tracking, and commission payouts.

list_affiliatescreate_affiliateget_earnings

qr_codes

platform

Generate QR codes for products, orders, payments, and custom URLs.

generate_qrlist_codesget_analytics

phone

phone

SMS messaging, phone number management, and conversation threads.

send_smslist_conversationsget_number

social

marketing

Social media posting, scheduling, and engagement tracking.

postschedulelist_postsget_engagement

Content5 tools

documents

documents

Generate invoices, packing slips, receipts, and custom PDF documents.

generate_documentlist_documentsget_document

image_gen

media

Generate product images, marketing graphics, and visual assets with AI.

generate_imageedit_imageupscale

video_gen

media

Create product videos, ads, and social media content from prompts or templates.

generate_videoget_statuslist_videos

media

media

Upload, organize, and transform media assets for products and marketing.

uploadlist_mediatransformdelete

remove_bg

media

Remove backgrounds from product images using AI segmentation.

remove_backgroundbatch_remove

Platform15 tools

workflows

workflows

Create and trigger automation workflows for business processes.

list_workflowstrigger_workflowget_status

browser

platform

Headless browser automation for web scraping, screenshots, and form filling.

navigatescreenshotextractclick

kali

platform

Security scanning and penetration testing tools for your storefront.

scan_urlcheck_headersvulnerability_report

store

platform

Store settings, configuration, plan details, and billing information.

get_storeupdate_settingsget_plan

storefront

storefront

Storefront theme, layout, navigation, and public-facing configuration.

get_configupdate_themepreview

api_keys

platform

Create, rotate, and revoke API keys for programmatic access.

list_keyscreate_keyrevoke_key

api_docs

platform

Retrieve API documentation, schemas, and endpoint specifications.

get_speclist_endpointsget_schema

telemetry

platform

Query application telemetry, spans, errors, and performance metrics.

query_spansquery_errorsget_metrics

audit_trail

platform

View audit logs of all actions taken across agents, users, and API keys.

list_eventsget_eventexport

whale_login

platform

Authenticate and manage sessions for the WhaleTools platform.

loginrefresh_tokenlogout

whale_status

platform

Check platform health, service status, and system-wide alerts.

get_statusget_incidentssubscribe

whale_stores

platform

List and switch between stores in a multi-store setup.

list_storesswitch_storeget_current

local_agent

platform

Manage local agent nodes for on-premise task execution.

list_nodesget_noderun_task

launch_cluster

platform

Provision and manage compute clusters for heavy processing tasks.

launchget_statusterminate

webhooks_mgmt

platform

Register, test, and manage webhook endpoints for event subscriptions.

list_webhookscreate_webhooktestdelete

Operations4 tools

supply_chain

inventory

Supplier management, purchase orders, lead times, and cost tracking.

list_supplierscreate_potrack_shipment

locations

inventory

Manage physical store locations, warehouses, and fulfillment centers.

list_locationscreate_locationupdate_location

wallet

commerce

Digital wallet management, stored payment methods, and balances.

get_balanceadd_fundslist_transactions

pipeline

crm

Sales pipeline management with deals, stages, and forecasting.

list_dealscreate_dealmove_stageget_forecast

Custom Tool Templates

Extend the MCP server with custom tools that your agents can call. Define HTTP webhook tools, JavaScript sandbox tools, or register existing API endpoints.

Tool Definition Schema

Every custom tool follows a standard schema with a name, description, input parameters, and an execution handler.

tool-definition.json
{
"name": "check_warehouse_stock",
"description": "Check real-time stock levels at a specific warehouse",
"category": "inventory",
"input_schema": {
"type": "object",
"properties": {
"sku": {
"type": "string",
"description": "Product SKU to check"
},
"warehouse_id": {
"type": "string",
"description": "Warehouse location identifier"
}
},
"required": ["sku"]
},
"handler": {
"type": "webhook",
"url": "https://your-api.com/stock/check",
"method": "POST",
"headers": {
"Authorization": "Bearer {{secrets.WAREHOUSE_API_KEY}}"
}
},
"requires_approval": false,
"visibility": "store"
}

HTTP Webhook Tools

Webhook tools forward the tool call to an external HTTP endpoint. The input arguments are sent as the request body, and the response is returned to the agent.

bash
curl -X POST https://gateway.whaletools.dev/v1/stores/{storeId}/custom-tools \
-H "Authorization: Bearer wt_live_..." \
-H "Content-Type: application/json" \
-d '{
"name": "lookup_shipping_rate",
"description": "Get shipping rates from carrier API",
"input_schema": {
"type": "object",
"properties": {
"origin_zip": { "type": "string" },
"destination_zip": { "type": "string" },
"weight_oz": { "type": "number" }
},
"required": ["origin_zip", "destination_zip", "weight_oz"]
},
"handler": {
"type": "webhook",
"url": "https://your-api.com/shipping/rates",
"method": "POST",
"headers": {
"X-Carrier-Key": "{{secrets.CARRIER_KEY}}"
},
"timeout_ms": 5000
}
}'

JavaScript Sandbox Tools

Sandbox tools run JavaScript in an isolated V8 environment. They have access to the tool input and a limited set of APIs. Execution is capped at 10 seconds.

sandbox-tool.json
{
"name": "calculate_margin",
"description": "Calculate profit margin for a product",
"input_schema": {
"type": "object",
"properties": {
"cost": { "type": "number" },
"price": { "type": "number" }
},
"required": ["cost", "price"]
},
"handler": {
"type": "javascript",
"code": "const margin = ((input.price - input.cost) / input.price) * 100; return { margin: margin.toFixed(2) + '%', profit: (input.price - input.cost).toFixed(2) };"
}
}

Registering via API

Register, update, and manage custom tools through the REST API. Tools are scoped to your store and immediately available to all connected MCP clients.

http
# List all custom tools
GET /v1/stores/{storeId}/custom-tools
# Create a custom tool
POST /v1/stores/{storeId}/custom-tools
# Update a tool
PATCH /v1/stores/{storeId}/custom-tools/{toolId}
# Delete a tool
DELETE /v1/stores/{storeId}/custom-tools/{toolId}
# Test a tool with sample input
POST /v1/stores/{storeId}/custom-tools/{toolId}/test
Body: { "input": { "sku": "WHALE-001" } }

Tool Execution Audit

Every tool execution is logged with full context: which agent called it, what input was provided, the result, and how long it took. Query execution logs for debugging, compliance, and usage tracking.

Query Executions

http
# List recent tool executions
GET /v1/stores/{storeId}/tool-executions
?tool=products # Filter by tool name
&agent_id=72d7aaa8-... # Filter by agent
&status=success # success | error | timeout | pending_approval
&from=2026-03-01T00:00:00Z # Start date
&to=2026-03-10T23:59:59Z # End date
&limit=50 # Results per page
&offset=0 # Pagination offset

Response Format

response.json
{
"executions": [
{
"id": "exec_8f3a2b1c",
"tool": "orders",
"action": "create_order",
"agent_id": "72d7aaa8-2e8b-48a0-a38d-f332f69600bb",
"agent_name": "Sales Assistant",
"status": "success",
"duration_ms": 342,
"input": {
"customer_id": "cust_abc123",
"items": [{ "product_id": "prod_xyz", "quantity": 2 }]
},
"output": {
"order_id": "ord_789def",
"total": 59.98
},
"created_at": "2026-03-10T14:23:01Z"
}
],
"total": 1847,
"limit": 50,
"offset": 0
}

Duration Tracking

Each execution includes duration_ms measuring end-to-end processing time. Use this to identify slow tools, set timeout thresholds, and optimize agent performance.

342ms

Avg latency

99.2%

Success rate

1,847

Executions today

12

Unique tools

Tool Approval Workflow

Gate sensitive tool executions behind human approval. When an agent calls a tool that requires approval, execution pauses until a team member approves or rejects the action.

Configuring Approval Gates

Set requires_approval on any tool or specific actions within a tool. You can also set conditional approval rules based on input thresholds.

approval-config.json
// Configure approval at the tool level
PATCH /v1/stores/{storeId}/agents/{agentId}/tool-config
{
"tool_overrides": {
"orders": {
"requires_approval": ["create_order", "cancel_order"],
"auto_approve": ["list_orders", "get_order"]
},
"inventory": {
"requires_approval": true,
"approval_conditions": {
"adjust_stock": {
"when": "Math.abs(input.quantity) > 100",
"message": "Large stock adjustment requires approval"
}
}
}
}
}

Approval and Rejection Flow

1

Agent calls a gated tool

The execution is created with status pending_approval. The agent receives a hold response and waits.

2

Notification sent to approvers

Team members with the approver role receive a notification via email, dashboard alert, or webhook. The notification includes the tool name, input arguments, and the agent that triggered it.

3

Approve or reject

Respond via the API or the dashboard:

http
# Approve the execution
POST /v1/stores/{storeId}/tool-executions/{execId}/approve
{ "comment": "Looks good, proceed." }
# Reject the execution
POST /v1/stores/{storeId}/tool-executions/{execId}/reject
{ "reason": "Quantity too high, please verify." }
4

Execution completes or aborts

On approval, the tool executes normally and the result is returned to the agent. On rejection, the agent receives the rejection reason and can adjust its approach.

Timeout Behavior

Pending approvals expire after a configurable timeout (default: 30 minutes). When an approval times out:

timeout_action: "reject"

The execution is automatically rejected. The agent receives a timeout error. This is the default.

timeout_action: "approve"

The execution proceeds automatically after the timeout elapses. Use for low-risk tools where you want oversight without blocking.

timeout_action: "escalate"

The approval request is escalated to a secondary approver group. If no response after the second timeout, it is rejected.

timeout-config.json
{
"requires_approval": true,
"approval_timeout_minutes": 15,
"timeout_action": "reject",
"escalation_group": "store-managers"
}

MCP Authentication

The MCP server supports multiple authentication methods. All methods ultimately resolve to a store context and a set of scopes that determine which tools the client can access.

API Key Authentication

The simplest method. Generate a key from your dashboard and pass it as an environment variable or HTTP header.

text
# stdio transport — set as environment variable
{
"env": {
"WHALETOOLS_API_KEY": "wt_live_sk_a1b2c3d4..."
}
}
# HTTP/SSE transport — set as Authorization header
Authorization: Bearer wt_live_sk_a1b2c3d4...

API keys are scoped to a single store. Each key has a set of permissions that control which tools it can access. Keys prefixed with wt_live_ are production keys; wt_test_ keys operate in sandbox mode.

OAuth Token Flow

For applications that need user-delegated access. The OAuth flow issues a JWT token scoped to the user and store.

http
# 1. Redirect user to authorization
GET https://whaletools.dev/auth/authorize
?client_id=your-app-id
&redirect_uri=https://your-app.com/callback
&scope=products:read orders:read orders:write
&response_type=code
# 2. Exchange authorization code for tokens
POST https://gateway.whaletools.dev/v1/auth/token
{
"grant_type": "authorization_code",
"code": "auth_code_from_callback",
"client_id": "your-app-id",
"client_secret": "your-app-secret",
"redirect_uri": "https://your-app.com/callback"
}
# Response:
{
"access_token": "eyJhbG...",
"refresh_token": "rt_...",
"expires_in": 3600,
"token_type": "Bearer",
"scope": "products:read orders:read orders:write"
}

Scope Requirements per Tool

Each tool requires at least one matching scope. Scopes follow a resource:action pattern. A bare scope (e.g., products) grants both read and write access.

Tool
Required Scopes
products
productsproducts:readproducts:write
orders
ordersorders:readorders:write
customers
customerscustomers:readcustomers:writecrm
inventory
inventoryinventory:readinventory:write
analytics
analyticsanalytics:read
email
marketingmarketing:write
voice
phonephone:write
documents
documentsdocuments:readdocuments:write
workflows
workflowsworkflows:readworkflows:write
browser
platform
image_gen
mediamedia:writecreations
video_gen
mediamedia:writecreations
web_search
platform
meta_ads
marketingmarketing:write
google_ads
marketingmarketing:write
media
mediamedia:readmedia:write
collections
catalogcatalog:write
discovery
catalogcatalog:read
enrichment
platform
embeddings
platform
llm
aiai:write
kali
platform
store
platformplatform:read
storefront
storefrontstorefront:readstorefront:write
supply_chain
inventoryinventory:write
locations
inventoryinventory:write
api_keys
platformplatform:write
api_docs
platformplatform:read
telemetry
platformplatform:read
audit_trail
platformplatform:read
whale_login
platform
whale_status
platformplatform:read
whale_stores
platformplatform:read
local_agent
platformplatform:write
remove_bg
mediamedia:write
launch_cluster
platformplatform:write
loyalty
commercecommerce:readcommerce:write
coupons
commercecommerce:readcommerce:write
fulfillment
ordersorders:write
segments
customerscustomers:readcrm
campaigns
marketingmarketing:readmarketing:write
reviews
catalogcatalog:readcatalog:write
tax
commercecommerce:read
webhooks_mgmt
platformplatform:write
affiliates
commercecommerce:readcommerce:write
qr_codes
platform
phone
phonephone:readphone:write
social
marketingmarketing:write
wallet
commercecommerce:readcommerce:write
pipeline
crmcrm:readcrm:write
invoices
commercecommerce:readcommerce:write
wholesale
commercecommerce:readcommerce:write

Scope best practices

Request the minimum scopes your integration needs. A read-only dashboard only needs products:read analytics:read.

Use :read suffixed scopes when your tool should never modify data. The MCP server enforces scope checks before every execution.

The platform scope grants access to administrative tools. Only grant this to trusted internal integrations.