Agentic Returns Integration

Overview

The Agentic Returns Integration enables AI agents and chatbots to guide shoppers through the Happy Returns return flow using the Model Context Protocol (MCP). This allows third-party integration partners to build conversational return experiences where an AI assistant can look up orders, present return options, and submit returns on behalf of shoppers.

The integration exposes a set of MCP tools that follow a sequential, guided flow. Each tool returns structured data and navigation metadata that tells the agent which step to perform next.

Supported platforms

Agentic Returns currently supports retailers on the Shopify platform. Retailers on other platforms will receive a redirect to the merchant’s return portal or customer support.

Supported drop-off methods

  • Return Bar — Shoppers drop off items at a Happy Returns Return Bar location. No box or label needed.
  • Mail — Shoppers receive a prepaid shipping label and mail items back via the designated carrier.

Architecture

ComponentDescription
MCP ServerStateless HTTP service exposing MCP tools at POST /returns/mcp via the MCP specification (version 2025-11-25).
Session StoreRedis-backed session management with configurable TTL (default 15 minutes). Sessions track return flow state across tool calls.
TransportStreamable HTTP transport (stateless mode). Session continuity is managed by the application-level session_id, not the MCP transport session.

Authentication

This integration uses machine-to-machine (M2M) OAuth2 client_credentials flow. Dynamic Client Registration (DCR), Client-Initiated Metadata Discovery (CIMD), and OpenID Connect (OIDC) are not supported.

1. Obtain credentials

Contact Happy Returns to receive a client_id and client_secret for your integration.

2. Generate a bearer token

Exchange your credentials for an access token:

POST https://mcp.happyreturns.com/oauth2/token
Content-Type: application/x-www-form-urlencoded

grant_type=client_credentials&client_id=YOUR_CLIENT_ID&client_secret=YOUR_CLIENT_SECRET&scope=returns/mcp

Sample response:

{
  "access_token": "eyJhbGciOiJSUzI1NiIsInR5cCI6...",
  "expires_in": 3600,
  "token_type": "Bearer"
}

3. Call MCP tools

Include the bearer token in the Authorization header on every request to the MCP endpoint:

POST https://mcp.happyreturns.com/returns/mcp
Authorization: Bearer YOUR_ACCESS_TOKEN
Content-Type: application/json

Token lifecycle

You are responsible for caching the access token and refreshing it before expiry. The expires_in field in the token response indicates the token’s TTL in seconds. Generate a new token before the current one expires to avoid service interruptions.

Tokens are bound to your client identity. All tool calls within a return session must use the same client credentials. Using a different client’s token mid-session will result in a CLIENT_MISMATCH error.

Rate limiting

Requests are rate-limited per client. When rate-limited, the server returns HTTP 429. Implement exponential backoff in your retry logic.


Return Flow

The return flow consists of six sequential steps. Each tool response includes a flow object that guides the agent to the next step.

1
getPurchaseDetails Look up the order by retailer ID, order number, and zip code. Creates a session and returns returnable items.
2
selectItems Select one or more items for return. Returns available return reasons for each item.
3
selectReturnReasons Submit return reasons (and sub-reasons if applicable) for each item. Returns available refund methods.
4
selectRefundMethods Submit refund method selections. Returns available drop-off methods (Return Bar and/or mail).
5
selectDropoffMethod Select a drop-off method. Returns a refund preview with itemized details and totals.
6
startReturn Submit the return. Returns confirmation details including the express code, QR code or shipping label, and return status page URL.

resetFlow can be called at any point to discard the session and restart from step 1.


Session Management

Session lifecycle

  • Created — When getPurchaseDetails succeeds. A unique session_id is returned.
  • Active — The session tracks state as tools are called (selected items, reasons, refund methods, drop-off payload).
  • Completed — After startReturn succeeds. The session is marked as completed and only resetFlow is available.
  • Expired — Sessions expire after the configured TTL (default 15 minutes of inactivity). Expired sessions return SESSION_NOT_FOUND.

Concurrency

A Redis-based tool lock ensures that only one tool call executes against a session at a time. If a concurrent call is attempted, the server returns SESSION_PROCESSING_BUSY — the agent should wait briefly and retry.

Idempotency

startReturn is idempotent: if the return was already submitted, calling it again with the same session returns the cached confirmation response rather than creating a duplicate return.


Flow Navigation

Every tool response includes a flow object with navigation metadata:

FieldTypeDescription
current_stepintegerCurrent position in the flow (1–6).
max_stepsintegerAlways 6.
next_toolstringSuggested next tool to call. Empty after completion.
allowed_toolsstring[]Tools that may be called in the current state. Calling a tool not in this list returns TOOL_NOT_ALLOWED.
previous_toolobjectThe most recent tool call (name and parameters). Useful for context when resuming a flow or debugging. Not present in the getPurchaseDetails response.

Your agent should always check allowed_tools before making a tool call. The flow engine dynamically computes which tools are available based on session state.


Agent Guidance Fields

Every tool response includes two guidance fields in the structured content:

FieldDescription
agent_instructionsHuman-readable text the agent should relay to the shopper. Mirrors the content[].text in the MCP response.
agent_requirementsMandatory constraints the agent must follow. Present only when product or legal requirements apply (e.g. displaying the privacy policy, presenting Return Bar before mail).

Your agent implementation must honor agent_requirements when present. These include legal requirements such as displaying the Happy Returns privacy policy, and product requirements such as presenting Return Bar drop-off options before mail options.


Error Handling

When a tool call fails, the response includes:

  • isError: true in the MCP result envelope
  • An error_code field in the structured content identifying the failure type
  • An agent_instructions message suitable for display to the shopper

Common error codes

Error CodeDescriptionRecovery
INVALID_INPUTMissing or malformed parametersCorrect the input and retry
SESSION_NOT_FOUNDSession expired or not foundCall getPurchaseDetails to start a new session
SESSION_COMPLETEDReturn already submittedCall getPurchaseDetails for a new return
CLIENT_MISMATCHSession belongs to a different clientEnsure all tool calls within a session use the same client credentials
TOOL_NOT_ALLOWEDTool not available in current stateCheck flow.allowed_tools and call an allowed tool
SERVICE_ERRORInternal service failureRetry with exponential backoff
SESSION_PROCESSING_BUSYAnother request in progressWait briefly and retry
ORDER_NOT_FOUNDOrder not foundVerify retailer ID, order number, and zip code
RETAILER_NOT_FOUNDRetailer ID not recognizedVerify the retailer ID
RETAILER_NOT_SUPPORTEDNon-Shopify platformDirect shopper to the merchant's return portal
NO_RETURNABLE_ITEMSNo items eligible for returnInform the shopper; check item details for reasons
ITEM_NOT_FOUNDItem ID not in the orderUse item IDs from getPurchaseDetails
ITEM_NOT_ELIGIBLEItem not returnableSelect a different item
INVALID_REFUND_METHODInvalid refund method IDUse IDs from selectReturnReasons response
INVALID_DROPOFFInvalid drop-off method IDUse IDs from selectRefundMethods response
NO_DROPOFF_METHODSNo supported drop-off methodsDirect shopper to the merchant's return portal

See the API Reference for the complete list of error codes per tool.


MCP Transport Details

This integration uses the Streamable HTTP transport type as defined in MCP specification version 2025-11-25.

Endpoint

All MCP tool calls are sent to a single endpoint:

POST https://mcp.happyreturns.com/returns/mcp
Authorization: Bearer YOUR_ACCESS_TOKEN
Content-Type: application/json

MCP clients (agent frameworks, SDKs) handle the protocol-level details of request framing and response parsing. Your integration should use an MCP-compatible client library to invoke tools by name with the appropriate arguments.

Response structure

Every tool response includes:

  • content — Human-readable text the agent can relay to the shopper.
  • structuredContent — Machine-readable data containing the tool’s output fields, agent_instructions, agent_requirements (when applicable), and the flow navigation object.
  • isError — Set to true on failure, with an error_code in structuredContent.

Tool discovery

MCP clients can discover available tools via the standard tools/list method, which returns tool names, descriptions, and input schemas. Refer to the MCP specification for protocol details.


Implementation Best Practices

1. Follow the flow

Always use the flow.next_tool hint and check flow.allowed_tools before making a tool call. The server enforces tool ordering based on session state.

2. Handle partial completions

When returning multiple items, selectRefundMethods may return pending_item_ids if some items still need reason or refund method selections. Loop through the remaining items before proceeding to drop-off selection.

3. Present Return Bar first

When both Return Bar and mail drop-off options are available, always present the Return Bar option first per the agent_requirements guidance. Only offer mail if the shopper declines or no Return Bar locations are available.

4. Display the privacy policy

On successful getPurchaseDetails, the agent_requirements field includes mandatory privacy policy copy. Your agent must display this to the shopper before presenting item details.

5. Handle service level for mail

In some regions (EU/UK), the mail drop-off method includes carrier_options with multiple service levels. The service_level parameter is required when calling selectDropoffMethod with mail in these cases.

6. Implement retry logic

For SERVICE_ERROR and SESSION_PROCESSING_BUSY responses, implement exponential backoff with a maximum of 3 retries. For SESSION_NOT_FOUND, start a fresh session with getPurchaseDetails.


Quick Reference

ToolStepPurposeKey Inputs
getPurchaseDetails1Look up order, create sessionretailer_id, order_number, zip_code
selectItems2Select items, get return reasonssession_id, item_ids
selectReturnReasons3Submit reasons, get refund methodssession_id, items[].reason
selectRefundMethods4Submit refund choices, get drop-off methodssession_id, items[].refund_method
selectDropoffMethod5Select drop-off, preview refundsession_id, dropoff_method_id
startReturn6Submit return, get confirmationsession_id
resetFlowDiscard session and start oversession_id

For detailed schemas, sample payloads, and the full error code reference, see the API Reference.