Module mcp
API
Declarations
Definitions

ballerina/mcp Ballerina library
Overview
Clients
mcp: Client
Represents an MCP client built on top of the Streamable HTTP transport.
Constructor
Initializes a new MCP client and establishes connection to the server. Performs protocol handshake and capability exchange. Client is ready for use after construction.
init (string serverUrl, *ClientConfiguration config)
- serverUrl string - MCP server URL
- config *ClientConfiguration - Client configuration including info and capabilities
subscribeToServerMessages
function subscribeToServerMessages() returns stream<JsonRpcMessage, StreamError?>|ClientError
Opens a server-sent events (SSE) stream for asynchronous server-to-client communication.
Return Type
- stream<JsonRpcMessage, StreamError?>|ClientError - Stream of JsonRpcMessages or a ClientError.
listTools
function listTools() returns ListToolsResult|ClientError
Retrieves the list of available tools from the server.
Return Type
- ListToolsResult|ClientError - List of available tools or a ClientError.
callTool
function callTool(CallToolParams params) returns CallToolResult|ClientError
Executes a tool on the server with the given parameters.
Parameters
- params CallToolParams - Tool execution parameters, including name and arguments.
Return Type
- CallToolResult|ClientError - Result of the tool execution or a ClientError.
close
function close() returns ClientError?
Closes the session and disconnects from the server.
Return Type
- ClientError? - A ClientError if closure fails, or nil on success.
Service types
mcp: AdvancedService
Defines an MCP service interface that handles incoming MCP requests.
onListTools
function onListTools() returns ListToolsResult|ServerError
onCallTool
function onCallTool(CallToolParams params) returns CallToolResult|ServerError
Parameters
- params CallToolParams -
mcp: Service
Defines a basic mcp service interface that handles incoming mcp requests.
Constants
mcp: INTERNAL_ERROR
Standard JSON-RPC 2.0 error code indicating that an internal error occurred on the server.
mcp: INVALID_PARAMS
Standard JSON-RPC 2.0 error code indicating that invalid method parameters were provided.
mcp: INVALID_REQUEST
Standard JSON-RPC 2.0 error code indicating that the JSON sent is not a valid request object.
mcp: JSONRPC_VERSION
mcp: LATEST_PROTOCOL_VERSION
mcp: METHOD_NOT_FOUND
Standard JSON-RPC 2.0 error code indicating that the method does not exist or is not available.
mcp: NOT_ACCEPTABLE
MCP library-defined error code indicating that the request is not acceptable.
mcp: PARSE_ERROR
Standard JSON-RPC 2.0 error code indicating that the JSON sent is not a valid JSON object.
mcp: SUPPORTED_PROTOCOL_VERSIONS
mcp: UNSUPPORTED_MEDIA_TYPE
MCP library-defined error code indicating that the media type is not supported.
Enums
mcp: NotificationMethod
JSON-RPC notification methods used for one-way communication in MCP
Members
mcp: RequestMethod
Standard JSON-RPC request methods supported by the MCP protocol
Members
Listeners
mcp: Listener
A server listener for handling MCP service requests.
Constructor
Initializes the Listener.
init (int|Listener listenTo, *ListenerConfiguration config)
- listenTo int|Listener - Either a port number (int) or an existing http:Listener.
- config *ListenerConfiguration - Listener configuration.
attach
function attach(Service|AdvancedService mcpService, string[]|string? name) returns Error?
Attaches an MCP service to the listener under the specified path(s).
Parameters
- mcpService Service|AdvancedService - Service to attach.
Return Type
- Error? - Error? if attachment fails.
detach
function detach(Service|AdvancedService mcpService) returns Error?
Detaches the MCP service from the listener.
Parameters
- mcpService Service|AdvancedService - Service to detach.
Return Type
- Error? - Error? if detachment fails.
'start
function 'start() returns Error?
Starts the listener (begin accepting connections).
Return Type
- Error? - Error? if starting fails.
gracefulStop
function gracefulStop() returns Error?
Gracefully stops the listener (completes active requests before shutting down).
Return Type
- Error? - Error? if graceful stop fails.
immediateStop
function immediateStop() returns Error?
Immediately stops the listener (terminates all connections).
Return Type
- Error? - Error? if immediate stop fails.
Annotations
mcp: ServiceConfig
Annotation to provide service configuration to MCP services.
mcp: Tool
Annotation to mark a function as an MCP tool configuration.
Records
mcp: Annotations
Optional annotations for the client. The client can use annotations to inform how objects are used or displayed
Fields
- audience? Role[] - Describes who the intended customer of this object or data is.
This can include multiple entries to indicate content useful for multiple audiences (e.g.,
["user", "assistant"]
).
- priority? decimal - Describes how important this data is for operating the server. A value of 1 means "most important," and indicates that the data is effectively required, while 0 means "least important," and indicates that the data is entirely optional.
mcp: AudioContent
Audio provided to or from an LLM.
Fields
- 'type "audio" - The type of content
- data string - The base64-encoded audio data
- mimeType string - The MIME type of the audio. Different providers may support different audio types.
- annotations? Annotations - Optional annotations for the client
mcp: BlobResourceContents
Binary resource contents
Fields
- Fields Included from *ResourceContents
- blob string - A base64-encoded string representing the binary data of the item.
mcp: CallToolParams
Parameters for the tools/call request
Fields
- Fields Included from *RequestParams
- _meta record { progressToken ProgressToken, anydata... }
- anydata...
- name string - The name of the tool to invoke
- arguments? record {} - Optional arguments to pass to the tool
mcp: CallToolRequest
Used by the client to invoke a tool provided by the server.
Fields
- method REQUEST_CALL_TOOL(default REQUEST_CALL_TOOL) - The JSON-RPC method name
- params CallToolParams - The parameters for the tool call
mcp: CallToolResult
The server's response to a tool call.
Fields
- content (TextContent|ImageContent|AudioContent|EmbeddedResource)[] - The content of the tool call result
- isError? boolean - Whether the tool call ended in an error. If not set, this is assumed to be false (the call was successful).
mcp: ClientCapabilities
Capabilities a client may support. Known capabilities are defined here, in this schema, but this is not a closed set: any client can define its own, additional capabilities.
Fields
- roots? record { listChanged boolean } - Present if the client supports listing roots.
- sampling? record {} - Present if the client supports sampling from an LLM.
mcp: ClientCapabilityConfiguration
Configuration for MCP client capabilities.
Fields
- capabilities? ClientCapabilities - Capabilities to be advertised by this client.
- enforceStrictCapabilities? boolean - Whether to enforce strict capabilities compliance.
mcp: ClientConfiguration
Configuration options for initializing an MCP client.
Fields
- sessionId string - Optional session identifier for continued interactions.
- info Implementation - Client information such as name and version.
- capabilityConfig? ClientCapabilityConfiguration - Client capabilities configuration.
mcp: EmbeddedResource
The contents of a resource, embedded into a prompt or tool call result.
Fields
- 'type "resource" - The type of content
- 'resource TextResourceContents|BlobResourceContents - The resource content
- annotations? Annotations - Optional annotations for the client
mcp: ImageContent
An image provided to or from an LLM.
Fields
- 'type "image" - The type of content
- data string - The base64-encoded image data
- mimeType string - The MIME type of the image. Different providers may support different image types.
- annotations? Annotations - Optional annotations for the client
mcp: Implementation
Describes the name and version of an MCP implementation.
Fields
- name string - The name of the implementation
- version string - The version of the implementation
mcp: InitializedNotification
This notification is sent from the client to the server after initialization has finished.
Fields
- Fields Included from *Notification
- method string
- params record { _meta record { anydata... }, anydata... }
- method NOTIFICATION_INITIALIZED(default NOTIFICATION_INITIALIZED) - The method identifier for the notification, must be "notifications/initialized"
mcp: InitializeResult
After receiving an initialize request from the client, the server sends this response.
Fields
- Fields Included from *Result
- _meta record { anydata... }
- anydata...
- protocolVersion string - The version of the Model Context Protocol that the server wants to use. This may not match the version that the client requested. If the client cannot support this version, it MUST disconnect.
- capabilities ServerCapabilities - The capabilities of the server.
- serverInfo Implementation - Information about the server implementation
- instructions? string - Instructions describing how to use the server and its features. This can be used by clients to improve the LLM's understanding of available tools, resources, etc. It can be thought of like a "hint" to the model. For example, this information MAY be added to the system prompt.
mcp: JsonRpcError
A response to a request that indicates an error occurred.
Fields
- jsonrpc JSONRPC_VERSION - The JSON-RPC protocol version
- id RequestId? - Identifier of the request
mcp: JsonRpcNotification
A notification which does not expect a response.
Fields
- Fields Included from *Notification
- method string
- params record { _meta record { anydata... }, anydata... }
- jsonrpc JSONRPC_VERSION - The JSON-RPC protocol version
mcp: JsonRpcRequest
A request that expects a response.
Fields
- Fields Included from *Request
- method string
- params RequestParams
- jsonrpc JSONRPC_VERSION - The JSON-RPC protocol version
- id RequestId - Identifier established by the client that should be returned in the response
mcp: JsonRpcResponse
A successful (non-error) response to a request.
Fields
- jsonrpc JSONRPC_VERSION - The JSON-RPC protocol version
- id RequestId - Identifier of the request
- result ServerResult - The result of the request
mcp: ListenerConfiguration
Configuration options for initializing an MCP listener.
mcp: ListToolsRequest
Sent from the client to request a list of tools the server has.
Fields
- Fields Included from *PaginatedRequest
- params RequestParams
- method REQUEST_LIST_TOOLS(default REQUEST_LIST_TOOLS) - The method identifier for this request
mcp: ListToolsResult
The server's response to a tools/list request from the client.
Fields
- Fields Included from *PaginatedResult
- nextCursor Cursor
- _meta record { anydata... }
- anydata...
- tools ToolDefinition[] - A list of tools available on the server.
mcp: McpToolConfig
Represents a tool configuration that can be used to define tools available in the MCP service.
Fields
- description? string - The description of the tool.
- schema? map<json> - The JSON schema for the tool's parameters.
mcp: Notification
Represents a notification.
Fields
- method string - The method name of the notification
- params? record { _meta record {} } - Additional parameters for the notification
mcp: PaginatedRequest
Represents a paginated request with optional cursor-based pagination.
Fields
- params? RequestParams - Optional pagination parameters
mcp: PaginatedResult
Result that supports pagination
Fields
- Fields Included from *Result
- _meta record { anydata... }
- anydata...
- nextCursor? Cursor - An opaque token representing the pagination position after the last returned result. If present, there may be more results available.
mcp: Request
Represents a generic request in the protocol
Fields
- method string - The method name for the request
- params? RequestParams - Optional parameters for the request
mcp: RequestParams
Parameters for the request
Fields
- _meta? record { progressToken ProgressToken } - Optional parameters for the request
mcp: ResourceContents
The contents of a specific resource or sub-resource.
Fields
- uri string - The URI of this resource.
- mimeType? string - The MIME type of this resource, if known.
mcp: Result
Base result type with common fields.
Fields
- _meta? record {} - This result property is reserved by the protocol to allow clients and servers to attach additional metadata to their responses.
mcp: ServerCapabilities
Capabilities that a server may support. Known capabilities are defined here, in this schema, but this is not a closed set: any server can define its own, additional capabilities.
Fields
- experimental? record { record {}... } - Experimental, non-standard capabilities that the server supports.
- logging? record { record {}... } - Present if the server supports sending log messages to the client.
- completions? record { record {}... } - Present if the server supports argument autocompletion suggestions.
- prompts? record { listChanged boolean } - Present if the server offers any prompt templates.
- tools? record { listChanged boolean } - Present if the server offers any tools to call.
mcp: ServerOptions
Represents the options for configuring an MCP server.
Fields
- capabilities? ServerCapabilities - Capabilities to advertise as being supported by this server.
- instructions? string - Optional instructions describing how to use the server and its features.
- enforceStrictCapabilities? boolean - Whether to enforce strict capabilities compliance.
mcp: ServiceConfiguration
Configuration for MCP service that defines server capabilities and metadata.
Fields
- info Implementation - Server implementation information
- options? ServerOptions - Optional server configuration options
mcp: TextContent
Text provided to or from an LLM.
Fields
- 'type "text" - The type of content
- text string - The text content of the message
- annotations? Annotations - Optional annotations for the client
mcp: TextResourceContents
Text resource contents
Fields
- Fields Included from *ResourceContents
- text string - The text of the item. This must only be set if the item can actually be represented as text (not binary data).
mcp: ToolAnnotations
Additional properties describing a Tool to clients. NOTE: all properties in ToolAnnotations are hints.
Fields
- title? string - A human-readable title for the tool.
- readOnlyHint? boolean - If true, the tool does not modify its environment. Default: false
- destructiveHint? boolean - If true, the tool may perform destructive updates to its environment.
If false, the tool performs only additive updates.
(This property is meaningful only when
readOnlyHint == false
) Default: true
- idempotentHint? boolean - If true, calling the tool repeatedly with the same arguments
will have no additional effect on the its environment.
(This property is meaningful only when
readOnlyHint == false
) Default: false
- openWorldHint? boolean - If true, this tool may interact with an "open world" of external entities. If false, the tool's domain of interaction is closed. For example, the world of a web search tool is open, whereas that of a memory tool is not. Default: true
mcp: ToolDefinition
Definition for a tool the client can call.
Fields
- name string - The name of the tool
- description? string - A human-readable description of the tool This can be used by clients to improve the LLM's understanding of available tools.
- inputSchema record { 'type "object" , properties record { record {}... }, required string[] } - A JSON Schema object defining the expected parameters for the tool.
- annotations? ToolAnnotations - Optional additional tool information.
Errors
mcp: ClientError
Error for failures occurring within client operations.
mcp: ClientInitializationError
Error for failures during client initialization.
mcp: Error
Defines the common base error type for this module.
mcp: HttpClientError
Error for failures during HTTP client operations.
mcp: InvalidMessageTypeError
Error when an invalid message type is received from the server.
mcp: JsonRpcMessageTransformationError
Error for JSON-RPC message transformation failures during streaming.
mcp: ListToolsError
Error for failures during tool listing operations.
mcp: MalformedResponseError
Error when the server response is malformed or unexpected.
mcp: MissingSseDataError
Error when required data is missing from an SSE event.
mcp: ProtocolVersionError
Error for protocol version negotiation failures.
mcp: ResponseParsingError
Error for failures while parsing HTTP response content.
mcp: ServerError
Errors for failures occurring during server operations.
mcp: SessionOperationError
Error for failures during session operations.
mcp: SseEventStreamError
Error for failures while processing SSE event streams.
mcp: SseStreamEstablishmentError
Error for failures during SSE stream establishment.
mcp: ToolCallError
Error for failures during tool execution operations.
mcp: TransportError
Error for failures during transport operations.
mcp: TypeConversionError
Error for failures converting JSON to JsonRpcMessage.
mcp: UninitializedTransportError
Error for operations attempted before transport initialization.
mcp: UnsupportedContentTypeError
Error for unsupported content types in HTTP responses.
Union types
mcp: JsonRpcMessage
JsonRpcMessage
Refers to any valid JSON-RPC object that can be decoded off the wire, or encoded to be sent.
mcp: ProgressToken
ProgressToken
A progress token, used to associate progress notifications with the original request.
mcp: Role
Role
The sender or recipient of messages and data in a conversation.
mcp: ServerResult
ServerResult
Represents a result sent from the server to the client.
Intersection types
mcp: StreamError
StreamError
Error for failures during streaming operations.
mcp: ServerResponseError
ServerResponseError
Error for invalid or unexpected responses from the server.
mcp: StreamableHttpTransportError
StreamableHttpTransportError
Error for failures during HTTP transport operations.
String types
mcp: Cursor
Cursor
An opaque token used to represent a cursor for pagination.
Import
import ballerina/mcp;
Metadata
Released date: 9 days ago
Version: 0.9.1
License: Apache-2.0
Compatibility
Platform: java21
Ballerina version: 2201.12.0
GraalVM compatible: Yes
Pull count
Total: 1248
Current verison: 309
Weekly downloads
Keywords
mcp
Contributors