Core and Manager APIs

This section covers MCP engine lifecycle, request handling, and transport manager APIs.

Engine Core

Header File

Functions

esp_err_t esp_mcp_create(esp_mcp_t **mcp)

Create an MCP instance.

Allocates and initializes a new MCP instance.

Parameters

mcp[out] Pointer to store the created MCP instance (must not be NULL)

Returns

  • ESP_OK: Server created successfully

  • ESP_ERR_NO_MEM: Memory allocation failed

esp_err_t esp_mcp_destroy(esp_mcp_t *mcp)

Destroy an MCP instance.

Frees all resources associated with the MCP instance, including all registered tools and message buffers. The function will attempt to clean up all resources even if some cleanup operations fail, and will log any errors encountered during cleanup.

Note

This function always completes the cleanup process and returns ESP_OK unless the server parameter is invalid. Any errors during resource cleanup are logged but do not affect the return value, as the caller cannot meaningfully recover from such errors anyway.

Parameters

mcp[in] Pointer to the MCP instance to destroy (must not be NULL)

Returns

  • ESP_OK: Cleanup completed (resources have been released, even if some errors occurred during cleanup)

  • ESP_ERR_INVALID_ARG: Invalid parameter (server is NULL)

esp_err_t esp_mcp_add_tool(esp_mcp_t *mcp, esp_mcp_tool_t *tool)

Add a tool to the MCP instance.

Adds a tool to the MCP instance.

Parameters
  • mcp[in] Pointer to the MCP instance (must not be NULL)

  • tool[in] Pointer to the tool to add (must not be NULL)

Returns

ESP_OK if successful, otherwise an error code

esp_err_t esp_mcp_remove_tool(esp_mcp_t *mcp, esp_mcp_tool_t *tool)

Remove a tool from the MCP instance.

Removes a tool from the MCP instance.

Parameters
  • mcp[in] Pointer to the MCP instance (must not be NULL)

  • tool[in] Pointer to the tool to remove (must not be NULL)

Returns

ESP_OK if successful, otherwise an error code

esp_err_t esp_mcp_add_resource(esp_mcp_t *mcp, esp_mcp_resource_t *res)

Add a resource to the MCP instance.

Parameters
  • mcp[in] MCP instance

  • res[in] Resource to add

Returns

ESP_OK on success

esp_err_t esp_mcp_remove_resource(esp_mcp_t *mcp, esp_mcp_resource_t *res)

Remove a resource from the MCP instance.

Parameters
  • mcp[in] MCP instance

  • res[in] Resource to remove

Returns

ESP_OK on success

esp_err_t esp_mcp_add_prompt(esp_mcp_t *mcp, esp_mcp_prompt_t *prompt)

Add a prompt to the MCP instance.

Parameters
  • mcp[in] MCP instance

  • prompt[in] Prompt to add

Returns

ESP_OK on success

esp_err_t esp_mcp_remove_prompt(esp_mcp_t *mcp, esp_mcp_prompt_t *prompt)

Remove a prompt from the MCP instance.

Parameters
  • mcp[in] MCP instance

  • prompt[in] Prompt to remove

Returns

ESP_OK on success

esp_err_t esp_mcp_set_completion_provider(esp_mcp_t *mcp, esp_mcp_completion_provider_t *provider)

Set completion provider for completion/complete support.

Parameters
  • mcp[in] MCP instance

  • provider[in] Completion provider, or NULL to clear

Returns

ESP_OK on success

esp_err_t esp_mcp_set_server_info(esp_mcp_t *mcp, const char *title, const char *description, const char *icons_json, const char *website_url)

Set server metadata for initialize response.

Sets optional server metadata fields that will be included in the serverInfo object of the initialize response per MCP 2025-11-25 spec.

Parameters
  • mcp[in] MCP instance

  • title[in] Human-readable server title (nullable)

  • description[in] Server description (nullable)

  • icons_json[in] Server icons JSON object string (nullable)

  • website_url[in] Server website URL (nullable)

Returns

ESP_OK on success

esp_err_t esp_mcp_set_instructions(esp_mcp_t *mcp, const char *instructions)

Set instructions for the client.

Sets the instructions field that will be included in the initialize response per MCP 2025-11-25 spec.

Parameters
  • mcp[in] MCP instance

  • instructions[in] Instructions for the client (nullable)

Returns

ESP_OK on success

esp_err_t esp_mcp_notify_log_message(esp_mcp_t *mcp, const char *level, const char *logger, const char *data_json_object)

Emit notifications/message to a client session.

Parameters
  • mcp[in] MCP instance

  • level[in] Log level string (e.g. “info”, “warning”, “error”)

  • logger[in] Logger name (nullable)

  • data_json_object[in] JSON object string payload

Returns

ESP_OK on success

esp_err_t esp_mcp_notify_progress(esp_mcp_t *mcp, const char *progress_token, double progress, double total, const char *message)

Emit notifications/progress to a client session.

Parameters
  • mcp[in] MCP instance

  • progress_token[in] Client-provided progress token

  • progress[in] Current progress value

  • total[in] Optional total value (set negative to omit)

  • message[in] Optional human-readable status text

Returns

ESP_OK on success

esp_err_t esp_mcp_set_incoming_request_handler(esp_mcp_t *mcp, esp_mcp_incoming_request_handler_t handler, void *user_ctx)

Set a generic handler for inbound MCP requests.

Parameters
  • mcp[in] MCP instance

  • handler[in] Handler function, or NULL to clear

  • user_ctx[in] User context pointer passed to handler

Returns

ESP_OK on success

esp_err_t esp_mcp_set_incoming_notification_handler(esp_mcp_t *mcp, esp_mcp_incoming_notification_handler_t handler, void *user_ctx)

Set a generic handler for inbound MCP notifications.

Parameters
  • mcp[in] MCP instance

  • handler[in] Handler function, or NULL to clear

  • user_ctx[in] User context pointer passed to handler

Returns

ESP_OK on success

esp_err_t esp_mcp_set_request_context(esp_mcp_t *mcp, const char *session_id, const char *auth_subject, bool is_authenticated)

Set current request context (transport-provided)

Note

This context is best-effort and is overwritten for each request.

Parameters
  • mcp[in] MCP instance

  • session_id[in] Session id from transport layer (nullable)

  • auth_subject[in] Authenticated principal/subject (nullable)

  • is_authenticated[in] True when current request has passed auth checks

Returns

ESP_OK on success

const char *esp_mcp_get_request_session_id(const esp_mcp_t *mcp)

Get session id from current request context.

Parameters

mcp[in] MCP instance

Returns

Session id string, or NULL if unavailable

esp_err_t esp_mcp_clear_session_state(esp_mcp_t *mcp, const char *session_id)

Clear session-scoped runtime state.

Parameters
  • mcp[in] MCP instance

  • session_id[in] Target session id (nullable)

Returns

ESP_OK on success

esp_err_t esp_mcp_request_roots_list(esp_mcp_t *mcp, const char *session_id, esp_mcp_server_req_cb_t cb, void *user_ctx, uint32_t timeout_ms, char *out_request_id, size_t out_request_id_len)

Emit server-initiated roots/list request to one session.

Parameters
  • mcp[in] MCP instance

  • session_id[in] Target MCP session id (nullable)

  • cb[in] Callback invoked when response arrives or times out

  • user_ctx[in] User context pointer passed to callback

  • timeout_ms[in] Request timeout in milliseconds (0 means default timeout)

  • out_request_id[out] Output buffer for generated request id (nullable)

  • out_request_id_len[in] Length of out_request_id buffer in bytes

Returns

ESP_OK on success

esp_err_t esp_mcp_request_sampling_create(esp_mcp_t *mcp, const char *session_id, const char *params_json, esp_mcp_server_req_cb_t cb, void *user_ctx, uint32_t timeout_ms, char *out_request_id, size_t out_request_id_len)

Emit server-initiated sampling/createMessage request to one session.

Parameters
  • mcp[in] MCP instance

  • session_id[in] Target MCP session id (nullable)

  • params_json[in] JSON object string for method params

  • cb[in] Callback invoked when response arrives or times out

  • user_ctx[in] User context pointer passed to callback

  • timeout_ms[in] Request timeout in milliseconds (0 means default timeout)

  • out_request_id[out] Output buffer for generated request id (nullable)

  • out_request_id_len[in] Length of out_request_id buffer in bytes

Returns

ESP_OK on success

esp_err_t esp_mcp_request_sampling_with_tools(esp_mcp_t *mcp, const char *session_id, const char *params_json, const char *tools_json, const char *tool_choice, esp_mcp_server_req_cb_t cb, void *user_ctx, uint32_t timeout_ms, char *out_request_id, size_t out_request_id_len)

Emit server-initiated sampling/createMessage with tools support.

This function sends a sampling request with tool definitions and toolChoice per MCP 2025-11-25 spec.

Parameters
  • mcp[in] MCP instance

  • session_id[in] Target MCP session id (nullable)

  • params_json[in] JSON object string for method params (excluding tools/toolChoice)

  • tools_json[in] JSON array string of tool definitions (nullable)

  • tool_choice[in] Tool choice mode: “auto”, “none”, or “required” (nullable)

  • cb[in] Callback invoked when response arrives or times out

  • user_ctx[in] User context pointer passed to callback

  • timeout_ms[in] Request timeout in milliseconds (0 means default timeout)

  • out_request_id[out] Output buffer for generated request id (nullable)

  • out_request_id_len[in] Length of out_request_id buffer in bytes

Returns

ESP_OK on success

esp_err_t esp_mcp_request_elicitation(esp_mcp_t *mcp, const char *session_id, const char *params_json, esp_mcp_server_req_cb_t cb, void *user_ctx, uint32_t timeout_ms, char *out_request_id, size_t out_request_id_len)

Emit server-initiated elicitation/create to one session.

Parameters
  • mcp[in] MCP instance

  • session_id[in] Target MCP session id (nullable)

  • params_json[in] JSON object string for method params

  • cb[in] Callback invoked when response arrives or times out

  • user_ctx[in] User context pointer passed to callback

  • timeout_ms[in] Request timeout in milliseconds (0 means default timeout)

  • out_request_id[out] Output buffer for generated request id (nullable)

  • out_request_id_len[in] Length of out_request_id buffer in bytes

Returns

ESP_OK on success

esp_err_t esp_mcp_request_elicitation_url(esp_mcp_t *mcp, const char *session_id, const char *params_json, const char *url, esp_mcp_server_req_cb_t cb, void *user_ctx, uint32_t timeout_ms, char *out_request_id, size_t out_request_id_len)

Emit server-initiated elicitation/create with URL mode.

This function sends an elicitation request with a URL that the client should open for user interaction per MCP 2025-11-25 spec.

Parameters
  • mcp[in] MCP instance

  • session_id[in] Target MCP session id (nullable)

  • params_json[in] JSON object string for method params (excluding url)

  • url[in] URL for the elicitation interaction

  • cb[in] Callback invoked when response arrives or times out

  • user_ctx[in] User context pointer passed to callback

  • timeout_ms[in] Request timeout in milliseconds (0 means default timeout)

  • out_request_id[out] Output buffer for generated request id (nullable)

  • out_request_id_len[in] Length of out_request_id buffer in bytes

Returns

ESP_OK on success

esp_err_t esp_mcp_request_tasks_get(esp_mcp_t *mcp, const char *session_id, const char *task_id, esp_mcp_server_req_cb_t cb, void *user_ctx, uint32_t timeout_ms, char *out_request_id, size_t out_request_id_len)

Emit server-initiated tasks/get request to one session.

Parameters
  • mcp[in] MCP instance

  • session_id[in] Target MCP session id (nullable)

  • task_id[in] Target task id

  • cb[in] Callback invoked when response arrives or times out

  • user_ctx[in] User context pointer passed to callback

  • timeout_ms[in] Request timeout in milliseconds (0 means default timeout)

  • out_request_id[out] Output buffer for generated request id (nullable)

  • out_request_id_len[in] Length of out_request_id buffer in bytes

Returns

ESP_OK on success

esp_err_t esp_mcp_request_tasks_result(esp_mcp_t *mcp, const char *session_id, const char *task_id, esp_mcp_server_req_cb_t cb, void *user_ctx, uint32_t timeout_ms, char *out_request_id, size_t out_request_id_len)

Emit server-initiated tasks/result request to one session.

Parameters
  • mcp[in] MCP instance

  • session_id[in] Target MCP session id (nullable)

  • task_id[in] Target task id

  • cb[in] Callback invoked when response arrives or times out

  • user_ctx[in] User context pointer passed to callback

  • timeout_ms[in] Request timeout in milliseconds (0 means default timeout)

  • out_request_id[out] Output buffer for generated request id (nullable)

  • out_request_id_len[in] Length of out_request_id buffer in bytes

Returns

ESP_OK on success

esp_err_t esp_mcp_request_tasks_cancel(esp_mcp_t *mcp, const char *session_id, const char *task_id, esp_mcp_server_req_cb_t cb, void *user_ctx, uint32_t timeout_ms, char *out_request_id, size_t out_request_id_len)

Emit server-initiated tasks/cancel request to one session.

Requires the peer to advertise capabilities.tasks.cancel.

Parameters
  • mcp[in] MCP instance

  • session_id[in] Target MCP session id (nullable)

  • task_id[in] Target task id

  • cb[in] Callback invoked when response arrives or times out

  • user_ctx[in] User context pointer passed to callback

  • timeout_ms[in] Request timeout in milliseconds (0 means default timeout)

  • out_request_id[out] Output buffer for generated request id (nullable)

  • out_request_id_len[in] Length of out_request_id buffer in bytes

Returns

ESP_OK on success

esp_err_t esp_mcp_request_tasks_list(esp_mcp_t *mcp, const char *session_id, const char *cursor, esp_mcp_server_req_cb_t cb, void *user_ctx, uint32_t timeout_ms, char *out_request_id, size_t out_request_id_len)

Emit server-initiated tasks/list request to one session.

Requires the peer to advertise capabilities.tasks.list.

Parameters
  • mcp[in] MCP instance

  • session_id[in] Target MCP session id (nullable)

  • cursor[in] Pagination cursor to continue from (nullable)

  • cb[in] Callback invoked when response arrives or times out

  • user_ctx[in] User context pointer passed to callback

  • timeout_ms[in] Request timeout in milliseconds (0 means default timeout)

  • out_request_id[out] Output buffer for generated request id (nullable)

  • out_request_id_len[in] Length of out_request_id buffer in bytes

Returns

ESP_OK on success

esp_err_t esp_mcp_handle_message(esp_mcp_t *mcp, const uint8_t *inbuf, uint16_t inlen, uint8_t **outbuf, uint16_t *outlen)

Handle one MCP JSON-RPC message and produce a response buffer.

This is a low-level helper that processes a single incoming MCP JSON-RPC message. If the input is a request, it produces a JSON-RPC response (UTF-8 JSON). If the input is a notification or response, it produces no output (outbuf==NULL).

Parameters
  • mcp[in] MCP instance

  • inbuf[in] Input buffer (UTF-8 JSON)

  • inlen[in] Input length in bytes

  • outbuf[out] Output buffer pointer (allocated by the engine, free with esp_mcp_free_response)

  • outlen[out] Output length in bytes

Returns

ESP_OK on success

esp_err_t esp_mcp_free_response(esp_mcp_t *mcp, uint8_t *outbuf)

Free a response buffer returned by esp_mcp_handle_message.

Parameters
  • mcp[in] MCP instance

  • outbuf[in] Output buffer to free (may be NULL)

Returns

ESP_OK on success

Type Definitions

typedef struct esp_mcp_s esp_mcp_t

MCP engine instance (protocol semantics + tool dispatch)

Opaque structure representing an MCP engine instance that handles MCP protocol semantics (e.g., tools/list, tools/call, ping, initialize) and tool execution.

Note

Naming/layering:

  • Public manager/router APIs use esp_mcp_mgr_* (see esp_mcp_mgr.h)

  • Transport implementations expose esp_mcp_transport_* tables (e.g., esp_mcp_transport_http)

  • This header defines the engine public API. For simplicity, the engine public APIs keep the short prefix esp_mcp_* (e.g., esp_mcp_create()).

typedef esp_err_t (*esp_mcp_incoming_request_handler_t)(const char *method, const char *params_json, char **out_result_json, void *user_ctx)

Generic handler for inbound MCP requests.

This callback is primarily useful when the SDK acts as an MCP client and receives server-initiated requests such as roots/list, sampling/createMessage, elicitation/create, or the tasks/ request family. Applications should allocate *out_result_json with malloc/calloc/strdup. When the callback returns ESP_OK and *out_result_json is NULL, the SDK replies with an empty result object {}.

Return value mapping:

  • ESP_OK: request handled successfully, reply with *out_result_json

  • ESP_ERR_NOT_SUPPORTED: request not handled, continue normal dispatch

  • ESP_ERR_INVALID_ARG: reply with JSON-RPC invalid params

  • other errors: reply with JSON-RPC internal error

Param method

[in] Request method string

Param params_json

[in] Request params JSON string, or NULL when params absent

Param out_result_json

[out] Result JSON string allocated by callback

Param user_ctx

[in] User context pointer

Return

esp_err_t status as described above

typedef esp_err_t (*esp_mcp_incoming_notification_handler_t)(const char *method, const char *params_json, void *user_ctx)

Generic handler for inbound MCP notifications.

This callback is useful for observing notifications that the SDK does not otherwise expose directly, for example notifications/roots/list_changed, notifications/message, notifications/progress, or notifications/tasks/status.

Param method

[in] Notification method string

Param params_json

[in] Notification params JSON string, or NULL when params absent

Param user_ctx

[in] User context pointer

Return

ESP_OK on success

typedef esp_err_t (*esp_mcp_server_req_cb_t)(int error_code, const char *request_name, const char *resp_json, void *user_ctx, uint32_t jsonrpc_request_id)

Callback for server-initiated request responses.

Param error_code

[in] 0/1 for application-level result, negative for JSON-RPC protocol error, positive esp_err_t for local/transport failure

Param request_name

[in] Logical request name/method

Param resp_json

[in] Response JSON payload

Param user_ctx

[in] User context pointer provided when request was sent

Return

ESP_OK on success

Manager / Transport

Header File

Functions

esp_err_t esp_mcp_mgr_init(esp_mcp_mgr_config_t config, esp_mcp_mgr_handle_t *handle)

Initialize MCP transport manager.

Initializes an MCP (Model Context Protocol) transport manager with the specified transport (HTTP, BLE, etc.). The transport manager handles communication between ESP32 devices and AI applications using the MCP protocol.

Parameters
  • config[in] MCP transport manager configuration (transport, config, server instance)

  • handle[out] Pointer to store the created MCP transport manager handle

Returns

  • ESP_OK: MCP transport manager initialized successfully

  • ESP_ERR_INVALID_ARG: Invalid arguments (NULL handle or invalid transport functions)

  • ESP_ERR_NO_MEM: Out of memory

esp_err_t esp_mcp_mgr_deinit(esp_mcp_mgr_handle_t handle)

Deinitialize MCP transport manager.

Deinitializes the MCP transport manager and releases all associated resources, including transport instances and configurations. The transport must be stopped (via esp_mcp_mgr_stop()) before deinitialization.

Parameters

handle[in] MCP transport manager handle

Returns

  • ESP_OK: MCP transport manager deinitialized successfully

  • ESP_ERR_INVALID_ARG: Invalid handle

esp_err_t esp_mcp_mgr_start(esp_mcp_mgr_handle_t handle)

Start MCP transport layer.

Starts the underlying transport layer (e.g., HTTP server, BLE service) to begin accepting MCP protocol messages from AI applications. The transport manager must be initialized before calling this function.

Parameters

handle[in] MCP transport manager handle

Returns

  • ESP_OK: Transport layer started successfully

  • ESP_ERR_INVALID_ARG: Invalid handle

  • ESP_ERR_FAIL: Failed to start transport layer (e.g., port already in use)

esp_err_t esp_mcp_mgr_stop(esp_mcp_mgr_handle_t handle)

Stop MCP transport layer.

Stops the underlying transport layer (e.g., HTTP server, BLE service) and stops accepting new MCP protocol messages. Existing connections may be gracefully closed.

Parameters

handle[in] MCP transport manager handle

Returns

  • ESP_OK: Transport layer stopped successfully

  • ESP_ERR_INVALID_ARG: Invalid handle

esp_err_t esp_mcp_mgr_register_endpoint(esp_mcp_mgr_handle_t handle, const char *ep_name, void *priv_data)

Register an MCP endpoint.

Registers an endpoint (e.g., “tools/list”, “tools/call”) for routing MCP protocol messages. Endpoints are used to organize different types of MCP operations. The endpoint will be accessible via the transport layer (e.g., HTTP path).

Parameters
  • handle[in] MCP transport manager handle

  • ep_name[in] Endpoint name (e.g., “mcp_server”, “tools/list”)

  • priv_data[in] Private data passed to the endpoint handler (typically NULL or MCP engine instance)

Returns

  • ESP_OK: Endpoint registered successfully

  • ESP_ERR_INVALID_ARG: Invalid arguments

  • ESP_ERR_INVALID_STATE: Endpoint already exists

  • ESP_ERR_NO_MEM: Memory allocation failed

esp_err_t esp_mcp_mgr_unregister_endpoint(esp_mcp_mgr_handle_t handle, const char *ep_name)

Unregister an MCP endpoint.

Removes an endpoint from the MCP transport manager. The endpoint will no longer accept MCP protocol messages. All associated resources are freed.

Parameters
  • handle[in] MCP transport manager handle

  • ep_name[in] Endpoint name to remove

Returns

  • ESP_OK: Endpoint removed successfully

  • ESP_ERR_INVALID_ARG: Invalid arguments

  • ESP_ERR_NOT_FOUND: Endpoint not found

esp_err_t esp_mcp_mgr_req_handle(esp_mcp_mgr_handle_t handle, const char *ep_name, const uint8_t *inbuf, uint16_t inlen, uint8_t **outbuf, uint16_t *outlen)

Handle an MCP protocol request.

Processes an incoming MCP protocol message (JSON-RPC 2.0 format) and routes it to the appropriate endpoint handler. The handler parses the message, executes the requested MCP operation (e.g., initialize, tools/list, tools/call), and returns the response. This function is typically called by transport layer implementations (e.g., HTTP handler) when receiving MCP protocol messages from AI applications.

Note

The caller is responsible for freeing the outbuf using cJSON_free() after sending the response.

Note

If the function returns an error, outbuf may be NULL or contain an error response.

Parameters
  • handle[in] MCP transport manager handle

  • ep_name[in] Endpoint name to route the request to (e.g., “mcp_server”)

  • inbuf[in] Input buffer containing the MCP protocol message (JSON-RPC 2.0 format, null-terminated)

  • inlen[in] Length of the input buffer in bytes

  • outbuf[out] Pointer to store the output buffer containing the MCP response JSON (caller must free with cJSON_free after use)

  • outlen[out] Pointer to store the output buffer length in bytes

Returns

  • ESP_OK: Request handled successfully, response available in outbuf

  • ESP_ERR_INVALID_ARG: Invalid arguments (NULL pointer or empty endpoint name)

  • ESP_ERR_NOT_FOUND: Endpoint not found

  • ESP_FAIL: Failed to process MCP request (parse error, tool execution error, etc.)

esp_err_t esp_mcp_mgr_perform_handle(esp_mcp_mgr_handle_t handle, const uint8_t *inbuf, uint16_t inlen)

Perform an outbound MCP request via the configured transport (client-side)

Sends a JSON-RPC request to a remote MCP server endpoint over the configured transport. The transport must implement the optional transport.request callback.

Parameters
  • handle[in] MCP transport manager handle

  • inbuf[in] Input buffer containing the MCP protocol message (JSON-RPC request)

  • inlen[in] Length of the input buffer in bytes

Returns

  • ESP_OK: Request performed successfully (fire-and-forget)

  • ESP_ERR_INVALID_ARG: Invalid arguments

  • ESP_ERR_NOT_SUPPORTED: Transport does not support outbound requests

  • Other: Transport-specific failure

esp_err_t esp_mcp_mgr_post_info_init(esp_mcp_mgr_handle_t handle, const esp_mcp_mgr_req_t *req)

Build and send initialize request to remote MCP server.

Constructs and sends an MCP initialize request to establish a session with a remote MCP server. The response will be delivered via the callback specified in the request structure.

Note

Lifecycle (outbound client): wait until the initialize response callback has run before sending other MCP requests. When the negotiated protocolVersion in the result is newer than 2024-11-05, the manager sends notifications/initialized automatically after a successful initialize result (unless it was already sent, including from your callback). You normally do not need to call esp_mcp_mgr_post_initialized() in addition.

Parameters
  • handle[in] MCP transport manager handle

  • req[in] Request structure containing endpoint name, callback, and initialization parameters (protocol_version, name, version)

Returns

  • ESP_OK: Request sent successfully

  • ESP_ERR_INVALID_ARG: Invalid arguments (NULL handle or request)

  • ESP_ERR_NOT_SUPPORTED: Transport does not support outbound requests

  • Other: Transport-specific failure

esp_err_t esp_mcp_mgr_post_tools_list(esp_mcp_mgr_handle_t handle, const esp_mcp_mgr_req_t *req)

Build and send tools/list request to remote MCP server.

Constructs and sends an MCP tools/list request to retrieve available tools from a remote MCP server. Supports cursor-based pagination. The response will be delivered via the callback specified in the request structure.

Parameters
  • handle[in] MCP transport manager handle

  • req[in] Request structure containing endpoint name, callback, and optional cursor for pagination

Returns

  • ESP_OK: Request sent successfully

  • ESP_ERR_INVALID_ARG: Invalid arguments (NULL handle or request)

  • ESP_ERR_NOT_SUPPORTED: Transport does not support outbound requests

  • Other: Transport-specific failure

esp_err_t esp_mcp_mgr_post_tools_call(esp_mcp_mgr_handle_t handle, const esp_mcp_mgr_req_t *req)

Build and send tools/call request to remote MCP server.

Constructs and sends an MCP tools/call request to execute a tool on a remote MCP server. The tool name and arguments (as JSON string) must be provided. The response will be delivered via the callback specified in the request structure.

Parameters
  • handle[in] MCP transport manager handle

  • req[in] Request structure containing endpoint name, callback, tool name, and arguments JSON

Returns

  • ESP_OK: Request sent successfully

  • ESP_ERR_INVALID_ARG: Invalid arguments (NULL handle, request, or missing tool_name)

  • ESP_ERR_NOT_SUPPORTED: Transport does not support outbound requests

  • Other: Transport-specific failure

esp_err_t esp_mcp_mgr_post_ping(esp_mcp_mgr_handle_t handle, const char *ep_name, esp_mcp_mgr_resp_cb_t cb, void *user_ctx)

Send ping to a remote MCP server.

esp_err_t esp_mcp_mgr_post_resources_list(esp_mcp_mgr_handle_t handle, const char *ep_name, const char *cursor, int limit, esp_mcp_mgr_resp_cb_t cb, void *user_ctx)

Send resources/list (optional cursor; limit < 0 omits limit field)

esp_err_t esp_mcp_mgr_post_resources_read(esp_mcp_mgr_handle_t handle, const char *ep_name, const char *uri, esp_mcp_mgr_resp_cb_t cb, void *user_ctx)

Send resources/read with uri.

esp_err_t esp_mcp_mgr_post_resources_subscribe(esp_mcp_mgr_handle_t handle, const char *ep_name, const char *uri, esp_mcp_mgr_resp_cb_t cb, void *user_ctx)

Send resources/subscribe for uri.

esp_err_t esp_mcp_mgr_post_resources_unsubscribe(esp_mcp_mgr_handle_t handle, const char *ep_name, const char *uri, esp_mcp_mgr_resp_cb_t cb, void *user_ctx)

Send resources/unsubscribe for uri.

esp_err_t esp_mcp_mgr_post_resources_templates_list(esp_mcp_mgr_handle_t handle, const char *ep_name, const char *cursor, int limit, esp_mcp_mgr_resp_cb_t cb, void *user_ctx)

Send resources/templates/list (optional cursor; limit < 0 omits limit field)

esp_err_t esp_mcp_mgr_post_prompts_list(esp_mcp_mgr_handle_t handle, const char *ep_name, const char *cursor, int limit, esp_mcp_mgr_resp_cb_t cb, void *user_ctx)

Send prompts/list (optional cursor; limit < 0 omits limit field)

esp_err_t esp_mcp_mgr_post_prompts_get(esp_mcp_mgr_handle_t handle, const char *ep_name, const char *name, const char *arguments_json, esp_mcp_mgr_resp_cb_t cb, void *user_ctx)

Send prompts/get (arguments_json may be NULL for {})

esp_err_t esp_mcp_mgr_post_completion_complete(esp_mcp_mgr_handle_t handle, const char *ep_name, const char *complete_params_json, esp_mcp_mgr_resp_cb_t cb, void *user_ctx)

Send completion/complete

Parameters
  • handle[in] MCP transport manager handle

  • ep_name[in] Endpoint name

  • complete_params_json[in] JSON object for params (ref + argument, etc.), not wrapped

  • cb[in] Response callback

  • user_ctx[in] User context for the callback

esp_err_t esp_mcp_mgr_post_logging_set_level(esp_mcp_mgr_handle_t handle, const char *ep_name, const char *level, esp_mcp_mgr_resp_cb_t cb, void *user_ctx)

Send logging/setLevel (e.g. level “info”)

esp_err_t esp_mcp_mgr_post_tasks_list(esp_mcp_mgr_handle_t handle, const char *ep_name, const char *cursor, esp_mcp_mgr_resp_cb_t cb, void *user_ctx)

Send tasks/list (optional cursor)

esp_err_t esp_mcp_mgr_post_tasks_get(esp_mcp_mgr_handle_t handle, const char *ep_name, const char *task_id, esp_mcp_mgr_resp_cb_t cb, void *user_ctx)

Send tasks/get

esp_err_t esp_mcp_mgr_post_tasks_result(esp_mcp_mgr_handle_t handle, const char *ep_name, const char *task_id, esp_mcp_mgr_resp_cb_t cb, void *user_ctx)

Send tasks/result

esp_err_t esp_mcp_mgr_post_tasks_cancel(esp_mcp_mgr_handle_t handle, const char *ep_name, const char *task_id, esp_mcp_mgr_resp_cb_t cb, void *user_ctx)

Send tasks/cancel

esp_err_t esp_mcp_mgr_post_request_json(esp_mcp_mgr_handle_t handle, const esp_mcp_mgr_json_req_t *req)

Build and send an arbitrary JSON-RPC request to a remote MCP peer.

This is a generic escape hatch for protocol methods that do not yet have a dedicated helper. It can be used for methods such as ping, resources/list, resources/read, resources/subscribe, resources/unsubscribe, prompts/list, prompts/get, completion/complete, logging/setLevel, tasks/list, tasks/get, tasks/result, and tasks/cancel.

Parameters
  • handle[in] MCP transport manager handle

  • req[in] Generic request descriptor

Returns

  • ESP_OK: Request sent successfully

  • ESP_ERR_INVALID_ARG: Invalid arguments or malformed params JSON

  • ESP_ERR_NOT_SUPPORTED: Transport does not support outbound requests

  • Other: Transport-specific failure

esp_err_t esp_mcp_mgr_post_notification_json(esp_mcp_mgr_handle_t handle, const esp_mcp_mgr_json_notification_t *notification)

Build and send an arbitrary JSON-RPC notification to a remote MCP peer.

This can be used for notifications such as notifications/initialized, notifications/cancelled, or notifications/roots/list_changed.

Parameters
  • handle[in] MCP transport manager handle

  • notification[in] Generic notification descriptor

Returns

  • ESP_OK: Notification sent successfully

  • ESP_ERR_INVALID_ARG: Invalid arguments or malformed params JSON

  • ESP_ERR_NOT_SUPPORTED: Transport does not support outbound requests

  • Other: Transport-specific failure

esp_err_t esp_mcp_mgr_post_initialized(esp_mcp_mgr_handle_t handle, const char *ep_name)

Send the standard notifications/initialized lifecycle notification.

Per MCP 2025-11-25, clients should send this notification after a successful initialize exchange has completed.

Note

When using esp_mcp_mgr_post_info_init() and related helpers, the manager usually sends this for you once the negotiated protocol requires it. Call this explicitly only if you are driving the session lifecycle yourself and need a manual notification.

Parameters
  • handle[in] MCP transport manager handle

  • ep_name[in] Endpoint name

Returns

  • ESP_OK: Notification sent successfully

  • ESP_ERR_INVALID_ARG: Invalid arguments

  • ESP_ERR_NOT_SUPPORTED: Transport does not support outbound requests

  • Other: Transport-specific failure

esp_err_t esp_mcp_mgr_open_stream(esp_mcp_mgr_handle_t handle)

Open stream channel for receiving server messages (e.g., GET SSE)

Uses the transport-specific stream opening mechanism. For Streamable HTTP transports this corresponds to opening the SSE stream channel.

Parameters

handle[in] MCP transport manager handle

Returns

  • ESP_OK: Stream opened successfully

  • ESP_ERR_NOT_SUPPORTED: Transport does not support stream opening

  • ESP_ERR_INVALID_ARG: Invalid handle

  • Other: Transport-specific failure

esp_err_t esp_mcp_mgr_set_bearer_token(esp_mcp_mgr_handle_t handle, const char *bearer_token)

Configure a static bearer token for the built-in HTTP client transport.

Passing NULL clears the configured token.

Parameters
  • handle[in] MCP transport manager handle

  • bearer_token[in] Bearer token string, or NULL to clear

Returns

  • ESP_OK: Token updated successfully

  • ESP_ERR_INVALID_ARG: Invalid handle

  • ESP_ERR_NOT_SUPPORTED: Underlying transport is not the built-in HTTP client

  • ESP_ERR_NO_MEM: Out of memory

esp_err_t esp_mcp_mgr_set_auth_callback(esp_mcp_mgr_handle_t handle, esp_mcp_mgr_auth_cb_t cb, void *user_ctx)

Configure an auth callback for the built-in HTTP client transport.

The callback is invoked after HTTP 401/403 auth challenges. Passing NULL clears the current callback and user context.

Parameters
  • handle[in] MCP transport manager handle

  • cb[in] Auth callback, or NULL to clear

  • user_ctx[in] Opaque user context for the callback

Returns

  • ESP_OK: Callback updated successfully

  • ESP_ERR_INVALID_ARG: Invalid handle

  • ESP_ERR_NOT_SUPPORTED: Underlying transport is not the built-in HTTP client

esp_err_t esp_mcp_mgr_set_sse_event_callback(esp_mcp_mgr_handle_t handle, esp_mcp_mgr_sse_event_cb_t cb, void *user_ctx)

Configure optional categorized SSE event callback (HTTP client transport)

Passing NULL clears the callback and user context.

Parameters
  • handle[in] MCP transport manager handle

  • cb[in] SSE callback, or NULL to clear

  • user_ctx[in] Opaque user context for callback

Returns

  • ESP_OK: Callback updated successfully

  • ESP_ERR_INVALID_ARG: Invalid handle

  • ESP_ERR_NOT_SUPPORTED: Underlying transport is not built-in HTTP client

esp_err_t esp_mcp_mgr_req_destroy_response(esp_mcp_mgr_handle_t handle, uint8_t *response_buffer)

Destroy a MCP response buffer.

Destroys a MCP response buffer and frees the memory. This function uses the message ID from the last request processed by the handler.

Note

This function uses the msg_id from the last request. For more precise control, use esp_mcp_mgr_req_destroy_response_by_id() instead.

Parameters
  • handle[in] MCP transport manager handle

  • response_buffer[in] MCP response buffer to destroy (currently unused, kept for API compatibility)

Returns

  • ESP_OK: Response buffer destroyed successfully

  • ESP_ERR_INVALID_ARG: Invalid arguments

  • ESP_ERR_NOT_FOUND: Message ID not found

esp_err_t esp_mcp_mgr_req_destroy_response_by_id(esp_mcp_mgr_handle_t handle, uint16_t id)

Destroy a MCP response buffer by message ID.

Destroys a MCP response buffer for the specified message ID and frees the memory. This is the recommended way to free response buffers when you know the message ID.

Note

This function should be called after sending the response to prevent memory leaks. Each handled request may allocate a response buffer that must be freed using this function or esp_mcp_mgr_req_destroy_response().

Parameters
  • handle[in] MCP transport manager handle

  • id[in] Message ID of the response to destroy

Returns

  • ESP_OK: Response buffer destroyed successfully

  • ESP_ERR_INVALID_ARG: Invalid arguments

  • ESP_ERR_NOT_FOUND: Message ID not found

esp_err_t esp_mcp_mgr_emit_message(esp_mcp_mgr_handle_t handle, const char *session_id, const char *jsonrpc_message)

Emit a JSON-RPC notification/request to clients (Streamable HTTP SSE)

This API enqueues a JSON-RPC message for delivery over the Streamable HTTP GET SSE channel. If session_id is NULL, the message is enqueued for all active sessions.

Parameters
  • handle[in] MCP manager handle

  • session_id[in] Optional MCP-Session-Id to target, or NULL for broadcast

  • jsonrpc_message[in] JSON string (must be newline-free)

Returns

ESP_OK on success, ESP_ERR_NOT_SUPPORTED if SSE not available

esp_err_t esp_mcp_mgr_set_request_context(esp_mcp_mgr_handle_t handle, const char *session_id, const char *auth_subject, bool is_authenticated)

Set per-request context for subsequent server-side request handling.

Transport implementations call this before invoking esp_mcp_mgr_req_handle(). The context is consumed by the engine while handling a single JSON-RPC message.

Parameters
  • handle[in] MCP manager handle

  • session_id[in] MCP session id (nullable)

  • auth_subject[in] Auth subject/principal (nullable)

  • is_authenticated[in] True if current request passed transport-layer auth

Returns

ESP_OK on success

esp_err_t esp_mcp_mgr_clear_session_state(esp_mcp_mgr_handle_t handle, const char *session_id)

Clear manager-side session state.

Clears state associated with a specific session, including duplicate-request tracking and other per-session runtime caches.

Parameters
  • handle[in] MCP manager handle

  • session_id[in] Target session id (nullable)

Returns

ESP_OK on success

esp_err_t esp_mcp_mgr_track_pending_request(esp_mcp_mgr_handle_t handle, const char *request_id, const char *session_id, const char *request_name, esp_mcp_mgr_resp_cb_t cb, void *user_ctx, uint32_t timeout_ms)

Track a server-initiated JSON-RPC request for response correlation.

The manager stores callback metadata keyed by request id. When a matching response arrives, callback will be invoked through existing response dispatch flow.

Parameters
  • handle[in] MCP manager handle

  • request_id[in] JSON-RPC request id

  • session_id[in] MCP session id used for request scoping (nullable)

  • request_name[in] Logical request name/method for callback identification

  • cb[in] Callback to invoke when response arrives

  • user_ctx[in] User context pointer passed to callback

  • timeout_ms[in] Expiration timeout in milliseconds (0 means default 30000)

Returns

ESP_OK on success

esp_err_t esp_mcp_mgr_cancel_pending_request(esp_mcp_mgr_handle_t handle, const char *request_id, const char *session_id)

Cancel a tracked pending request.

Removes pending request callback by request id and reports cancellation to callback.

Parameters
  • handle[in] MCP manager handle

  • request_id[in] JSON-RPC request id to cancel

  • session_id[in] MCP session id used for request scoping (nullable)

Returns

ESP_OK if cancelled, ESP_ERR_NOT_FOUND if no such request

esp_err_t esp_mcp_mgr_sweep_pending_requests(esp_mcp_mgr_handle_t handle)

Sweep and expire timed-out pending requests immediately.

Useful for transports to proactively trigger timeout callbacks even when no inbound responses are currently being processed.

Parameters

handle[in] MCP manager handle

Returns

ESP_OK on success

Structures

struct esp_mcp_mgr_auth_context_t

Authorization context delivered to auth callbacks.

String pointers remain valid only for the duration of the callback.

Public Members

int status_code

Status code that triggered auth handling

const char *request_url

Current MCP endpoint URL

const char *resource

OAuth resource indicator, if known

const char *required_scope

Scope requested by the challenge, if any

const char *resource_metadata_url

Protected-resource metadata URL used for discovery

const char *authorization_server

Selected authorization server issuer/base URL

const char *authorization_metadata_url

Authorization server metadata URL used for discovery

const char *issuer

Authorization server issuer

const char *authorization_endpoint

Authorization endpoint, if discovered

const char *token_endpoint

Token endpoint, if discovered

const char *registration_endpoint

Dynamic client registration endpoint, if discovered

bool pkce_s256_supported

True when authorization metadata advertises S256 PKCE support

struct esp_mcp_mgr_req_t

MCP request structure.

Structure for transmitting MCP requests.

Public Members

const char *ep_name

Endpoint name

esp_mcp_mgr_resp_cb_t cb

Response callback

void *user_ctx

User context

const char *protocol_version

Protocol version string, default “2025-11-25” if NULL

const char *name

Client name

const char *version

Client version

const char *title

Optional client title

const char *description

Optional client description

const char *icons_json

Optional client icons JSON array

const char *website_url

Optional client website URL

const char *capabilities_json

Optional client capabilities JSON object

struct esp_mcp_mgr_req_t::[anonymous]::[anonymous] init

Parameters for initialize request

const char *cursor

Cursor

int limit

tools/list: >=0 sends limit; <0 omits (use -1)

struct esp_mcp_mgr_req_t::[anonymous]::[anonymous] list

Parameters for tools/list request

const char *tool_name

Tool name

const char *args_json

Tool arguments JSON

struct esp_mcp_mgr_req_t::[anonymous]::[anonymous] call

Parameters for tools/call request

union esp_mcp_mgr_req_t::[anonymous] u

Union containing request-specific parameters

struct esp_mcp_mgr_json_req_t

Generic JSON-RPC request descriptor for client-side outbound MCP calls.

Public Members

const char *ep_name

Endpoint name

const char *method

JSON-RPC method name

const char *params_json

Optional params JSON object string

esp_mcp_mgr_resp_cb_t cb

Response callback

void *user_ctx

User context

struct esp_mcp_mgr_json_notification_t

Generic JSON-RPC notification descriptor for client-side outbound MCP notifications.

Public Members

const char *ep_name

Endpoint name

const char *method

JSON-RPC method name

const char *params_json

Optional params JSON object string

struct esp_mcp_transport_s

MCP transport function table.

Structure defining the function callbacks for a specific MCP transport implementation. Each transport (HTTP, BLE, etc.) provides its own implementation of these functions to handle protocol-specific operations like starting/stopping the transport layer and managing endpoints for MCP message routing.

Public Members

esp_err_t (*init)(esp_mcp_mgr_handle_t handle, esp_mcp_transport_handle_t *transport_handle)

Create a new transport instance

esp_err_t (*deinit)(esp_mcp_transport_handle_t handle)

Destroy a transport instance

esp_err_t (*start)(esp_mcp_transport_handle_t handle, void *config)

Start the transport layer (e.g., start HTTP server)

esp_err_t (*stop)(esp_mcp_transport_handle_t handle)

Stop the transport layer (e.g., stop HTTP server)

esp_err_t (*create_config)(const void *config, void **config_out)

Create transport-specific configuration

esp_err_t (*delete_config)(void *config)

Destroy transport-specific configuration

esp_err_t (*register_endpoint)(esp_mcp_transport_handle_t handle, const char *ep_name, void *priv_data)

Register an MCP endpoint for message routing

esp_err_t (*unregister_endpoint)(esp_mcp_transport_handle_t handle, const char *ep_name)

Unregister an MCP endpoint

esp_err_t (*request)(esp_mcp_transport_handle_t handle, const uint8_t *inbuf, uint16_t inlen)

Perform an outbound MCP request (client-side), optional, fire-and-forget

esp_err_t (*open_stream)(esp_mcp_transport_handle_t handle)

Open inbound stream channel (client-side), optional

esp_err_t (*emit_message)(esp_mcp_transport_handle_t handle, const char *session_id, const char *jsonrpc_message)

Emit server-side notification/message to connected stream clients

esp_err_t (*terminate)(esp_mcp_transport_handle_t handle)

Terminate the MCP session (client-side), optional

struct esp_mcp_mgr_config_t

MCP transport manager configuration structure.

Configuration structure for initializing an MCP transport manager instance. Specifies the transport to use (HTTP, BLE, etc.) and associated configuration.

Public Members

esp_mcp_transport_t transport

Transport function table (e.g., esp_mcp_transport_http)

void *config

Transport-specific configuration (e.g., HTTP server port, BLE service UUID)

void *instance

MCP instance context (esp_mcp_t *) for handling MCP protocol messages

Macros

ESP_MCP_JSONRPC_ID_UNSPEC

Sentinel: response id was non-numeric or missing (e.g. server string ids).

Type Definitions

typedef uint32_t esp_mcp_mgr_handle_t

MCP transport manager handle type.

Opaque handle representing an initialized MCP (Model Context Protocol) transport manager instance. The transport manager handles communication between ESP32 devices and AI applications using the MCP protocol over various transport layers (HTTP, BLE, etc.). Created by esp_mcp_mgr_init() and used for all subsequent MCP transport operations.

typedef uint32_t esp_mcp_transport_handle_t

MCP transport handle type.

Opaque handle representing an initialized MCP transport instance. A transport defines how MCP protocol messages are transmitted (e.g., HTTP, BLE). Created by the transport’s new() function and used for transport-specific operations.

typedef esp_err_t (*esp_mcp_mgr_resp_cb_t)(int error_code, const char *ep_name, const char *resp_json, void *user_ctx, uint32_t jsonrpc_request_id)

Response callback type for outbound requests.

This callback is invoked when a response is received for an outbound MCP request. The meaning of parameters depends on the response type:

Note

The callback is called synchronously. The ep_name and resp_json pointers are valid only during the callback execution. The framework will free these resources after the callback returns. The callback should NOT attempt to free these strings.

Param error_code

Error indicator or error code, meaning depends on resp_json:

  • If resp_json is not NULL and contains application result:

    • 0: Application-level success (result.isError = false or not present)

    • 1: Application-level error (result.isError = true)

  • If resp_json is not NULL and contains protocol error:

    • JSON-RPC error code (negative integer, e.g., -32601 for “Method not found”)

    • See MCP_ERROR_CODE_* constants in esp_mcp_error.h

  • If resp_json is NULL (parse failure):

    • esp_err_t error code (e.g., ESP_ERR_INVALID_ARG, ESP_ERR_NO_MEM)

Param ep_name

Endpoint name or tool name (may be NULL); valid only during callback execution, do NOT free

Param resp_json

Response JSON body, meaning depends on error_code:

  • If error_code is 0 or 1: Contains result object JSON (application-level response)

  • If error_code is negative (JSON-RPC error code): Contains error message string (protocol-level error)

  • If error_code is positive esp_err_t: NULL (parse failure) Valid only during callback execution, do NOT free

Param user_ctx

User context provided when sending the request

Param jsonrpc_request_id

Outbound JSON-RPC id when numeric (client requests); ESP_MCP_JSONRPC_ID_UNSPEC if unknown/non-numeric

Return

ESP_OK on success, or error code if callback processing failed

typedef esp_err_t (*esp_mcp_mgr_auth_cb_t)(const esp_mcp_mgr_auth_context_t *context, char *out_bearer_token, size_t out_bearer_token_len, void *user_ctx)

Auth callback used by the built-in transport layer.

The callback may perform application-defined OAuth handling and return a bearer token to retry the failed request. Set out_bearer_token to an empty string and return non-ESP_OK when no token can be provided.

typedef esp_err_t (*esp_mcp_mgr_sse_event_cb_t)(const char *channel_name, const char *event_name, const char *event_id, esp_mcp_sse_event_category_t category, const char *payload, void *user_ctx)

Optional SSE callback for built-in HTTP client stream events.

Called for each complete SSE event parsed by the stream channel.

typedef struct esp_mcp_transport_s esp_mcp_transport_t

MCP transport function table.

Structure defining the function callbacks for a specific MCP transport implementation. Each transport (HTTP, BLE, etc.) provides its own implementation of these functions to handle protocol-specific operations like starting/stopping the transport layer and managing endpoints for MCP message routing.

Enumerations

enum esp_mcp_sse_event_category_t

SSE event categories for optional stream callbacks.

Values:

enumerator ESP_MCP_SSE_EVENT_CATEGORY_UNKNOWN
enumerator ESP_MCP_SSE_EVENT_CATEGORY_JSONRPC_RESPONSE
enumerator ESP_MCP_SSE_EVENT_CATEGORY_NOTIFICATION_MESSAGE
enumerator ESP_MCP_SSE_EVENT_CATEGORY_NOTIFICATION_PROGRESS
enumerator ESP_MCP_SSE_EVENT_CATEGORY_NOTIFICATION_RESOURCES
enumerator ESP_MCP_SSE_EVENT_CATEGORY_NOTIFICATION_TASKS
enumerator ESP_MCP_SSE_EVENT_CATEGORY_NOTIFICATION_OTHER
enumerator ESP_MCP_SSE_EVENT_CATEGORY_NON_JSONRPC