@cloudbase/mcp
@cloudbase/mcp` provides a series of tools for building MCP, including
- Cloudbase Function Cloud Hosting support. Provides a framework for Function Cloud Hosting, focusing on MCP Server development, enabling quick access and deployment to Function Cloud Hosting.
Installation
npm i @cloudbase/mcp
Usage Example
Building MCP Server on Function Cloud Hosting
This code by default provides the MCP Server service at /messages
.
import { StreamableHTTPMCPServerRunner } from "@cloudbase/mcp/cloudrun";
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { z } from "zod";
const createServer = () => {
const server = new McpServer({
name: "hello-world",
version: "1.0.0",
})
server.registerTool("getUserAge", {
description: "Query the user's age",
inputSchema: {
userName: z.string().describe("Username"),
},
outputSchema: {
age: z.number().describe("Age"),
},
}, ({userName}) => {
let structuredContent
if (userName === "Zhang San") {
structuredContent = {
age: 18,
};
} else if (userName === "Li Si") {
structuredContent = {
age: 20,
};
} else {
throw new Error("Age of the user not found");
}
return {
structuredContent,
content: [
{
type: "text",
text: JSON.stringify(structuredContent),
}
]
}
})
return { server };
}
export const main = (event, context) => {
return StreamableHTTPMCPServerRunner.run(event, context,createServer)
}
API Reference
StreamableHTTPMCPServerRunner
The utility class for running MCP Server in Function Cloud Hosting provides the following functionalities:
- Routing determination
- Authentication
- Automatic processing of HTTP requests/responses
- Streamable HTTP Transport support
MCP Server can be run on Function Cloud Hosting with just a few lines of code:
// Function Cloud Hosting
// ...Omit the createServer function implementation
export const main = (event, context) => StreamableHTTPMCPServerRunner.run(event, context, createServer)
The above code provides the MCP Server service at /messages
, which by default intercepts requests using the cloud development accessToken from the HTTP Header, allowing only calls from apiKeys and administrator identities. Specific parameters can be passed to modify the default behavior:
// Function Cloud Hosting
// ...Omit the createServer function implementation
const runner = new StreamableHTTPMCPServerRunner(createServer,
{
verifyAccess: false // Controls whether to perform authentication interception
});
export const main = (event, context) => runner.run(event, context);
Import
import { StreamableHTTPMCPServerRunner } from '@cloudbase/mcp/cloudrun';
static run()
The static method on
StreamableHTTPMCPServerRunner` runs the MCP Server on Function Cloud Hosting with the default configuration.
// Function Cloud Hosting
// ...Omit the createServer function implementation
export const main = (event, context) => StreamableHTTPMCPServerRunner.run(event, context, createServer)
Parameters
Name | Type | Required | Description |
---|---|---|---|
event | Yes | Simply pass in the event parameter received by the Function Cloud Hosting. | |
context | Yes | Simply pass in the context parameter received by Function Cloud Hosting. | |
createServer | Yes | A function that returns an instance of the MCP Server |
new()
Creates an MCPServerRunner
instance, allowing parameters to be passed in to control the behavior of the run()
method.
// ...Omit the createServer function implementation
const runner = new MCPServerRunner(createServer,
{
verifyAccess: true // Controls whether to perform authentication interception
});
Parameters
Name | Type | Required | Description |
---|---|---|---|
createServer | function | Yes | A function that creates and returns an instance of the MCP Server |
prop | object | No | Controls the behavior of MCPServerRunner |
prop.verifyAccess | boolean | No | Controls whether to perform authentication interception. If set to true , only calls from apiKey and administrator identities are allowed. |
prop.sessionIdGenerator | () => string | No | A sessionId generator function. If provided, it will establish a stateful service. |
prop.sessionTimeout | number | No | sessionId expiration time (ms). This parameter takes effect only in stateful services |
run()
Based on the parameter configuration on the MCPServerRunner
instance, run the MCP Server on Function Cloud Hosting.
// Function Cloud Hosting
// ...Omit the process of creating an MCP Server instance
const runner = new MCPServerRunner(createServer,
{
verifyAccess: true // Controls whether to perform authentication interception
});
export const main = (event, context) => runner.run(event, context);
Parameters
Name | Type | Required | Description |
---|---|---|---|
event | Yes | Simply pass in the event parameter received by the Function Cloud Hosting. | |
context | Yes | Simply pass in the context parameter received by Function Cloud Hosting. |
MCPServerRunner
The utility class for running MCP Server in Function Cloud Hosting provides the following functionalities:
- Routing determination
- Authentication
- Automatic processing of HTTP requests/responses
- SSE Transport support
MCP Server can be run on Function Cloud Hosting with just a few lines of code:
// Function Cloud Hosting
// ...Omit the createServer function implementation
export const main = (event, context) => MCPServerRunner.run(event, context, createServer)
The above code provides the MCP Server service at /messages
, which by default intercepts requests using the cloud development accessToken from the HTTP Header, allowing only calls from apiKeys and administrator identities. Specific parameters can be passed to modify the default behavior:
// Function Cloud Hosting
// ...Omit the createServer function implementation
const runner = new MCPServerRunner(createServer,
{
verifyAccess: false // Controls whether to perform authentication interception
});
export const main = (event, context) => runner.run(event, context);
Import
import { MCPServerRunner } from '@cloudbase/mcp/cloudrun';
static run()
The static method on
MCPServerRunner` runs the MCP Server on Function Cloud Hosting with the default configuration.
// Function Cloud Hosting
// ...Omit the createServer function implementation
export const main = (event, context) => MCPServerRunner.run(event, context, createServer)
Parameters
Name | Type | Required | Description |
---|---|---|---|
event | Yes | Simply pass in the event parameter received by the Function Cloud Hosting. | |
context | Yes | Simply pass in the context parameter received by Function Cloud Hosting. | |
createServer | Yes | A function that returns an instance of the MCP Server |
new()
Creates an MCPServerRunner
instance, allowing parameters to be passed in to control the behavior of the run()
method.
// ...Omit the createServer function implementation
const runner = new MCPServerRunner(createServer,
{
verifyAccess: true // Controls whether to perform authentication interception
});
Parameters
Name | Type | Required | Description |
---|---|---|---|
createServer | function | Yes | A function that creates and returns an instance of MCP Server |
prop | object | No | Controls the behavior of MCPServerRunner |
prop.verifyAccess | boolean | No | Controls whether to perform authentication interception. If set to true , only calls from apiKey and administrator identities are allowed. |
run()
Based on the parameter configuration on the MCPServerRunner
instance, run the MCP Server on Function Cloud Hosting.
// Function Cloud Hosting
// ...Omit the process of creating an MCP Server instance
const runner = new MCPServerRunner(createServer,
{
verifyAccess: true // Controls whether to perform authentication interception
});
export const main = (event, context) => runner.run(event, context);
Parameters
Name | Type | Required | Description |
---|---|---|---|
event | Yes | Simply pass in the event parameter received by the Function Cloud Hosting. | |
context | Yes | Simply pass in the context parameter received by Function Cloud Hosting. |
CloudbaseMcpServer [deprecated]
[Deprecated] This class is deprecated. Compared to the early MCP official SDK, CloudbaseMcpServer
additionally provides support for outputSchema. Currently, the MCP official SDK has implemented support for outputSchema, and we recommend using the MCP official SDK directly.
The Cloudbase-extended MCP Server. Using this class allows for quick construction of an MCP Server instance. This class extends the McpServer from the Claude MCP SDK, adding a chaining invocation form to the tool()
method while retaining all other capabilities.
Import
import { CloudbaseMcpServer } from "@cloudbase/mcp/server";
tool()
Create a tool on this server. This method supports multiple invocation approaches.
Recommended Usage: Chaining Invocation
We recommend using chaining invocation: Trigger the chaining call by invoking tool()
with only one name
parameter. You can successively call description()
, inputSchema()
, outputSchema()
, and formatter()
to add different properties to the tool. Finally, complete the tool creation by calling .create()
and passing in the corresponding function implementation.
- The
description()
,inputSchema()
,outputSchema()
, andformatter()
calls appearing betweentool()
andcreate()
are all optional; any of these calls can be omitted. - The order of appearance for
description()
,inputSchema()
,outputSchema()
, andformatter()
is arbitrary; they can be called in any sequence. - Must ensure the chaining invocation starts with
tool()
and ends withcreate()
.
// ...Omit the process of creating a server instance
server
// Trigger chaining invocation by passing only one `name` parameter
.tool('add')
// Add parameters to the tool
.description('Adds two numbers')
// Add input parameter schema specification for the tool
.inputSchema({
a: z.number({
description: 'augend',
}),
b: z.number({
description: 'addend',
}),
})
// Add output parameter schema specification for the tool
.outputSchema({
result: z.number({
description: 'the sum of two numbers',
}),
})
// Add output parameter formatter to the tool
.formatter(({ a, b }, { result }) => {
return {
content: [
{
type: 'text',
text: `${a} + ${b} = ${result}`,
},
],
};
})
// Finally pass in the implementation function to complete the tool creation
.create(({ a, b }) => ({ result: a + b }));
Other Usage
Register a parameterless tool:
// Register a parameterless tool
server.tool('sayHello', () => {
return { content: [{ type: 'text', text: 'Hello World' }] }
})
Register a parameterless tool with description:
// Register a parameterless tool with description
server.tool('sayHello', 'Returns a simple greeting', () => {
return { content: [{ type: 'text', text: 'Hello World' }] }
})
Register a tool with parameters:
// Register a tool with parameters
server.tool('add', {
a: z.number(),
b: z.number()
}, ({ a, b }) => {
return { result: a + b }
})
Register a tool with description and parameters:
// Register a tool with description and parameters
server.tool('add', 'Adds two numbers', {
a: z.number(),
b: z.number()
}, ({ a, b }) => {
return { result: a + b }
})
PostClientTransport [deprecated]
[Important] This class is deprecated. Compared to the early official MCP SDK, PostClientTransport
provides more friendly support for stateless MCP Servers. The current official MCP SDK offers Streamable HTTP Transport, which can be used to build both stateless and stateful MCP Servers. For stateless services, we recommend directly using Streamable HTTP Transport.
Post Transport for MCP Client.
Import
import { PostClientTransport } from '@cloudbase/mcp/transport/client/post';
new()
Creates a PostClientTransport
instance, where the second argument opts
can be passed to control network request behavior.
const transport = new PostClientTransport(new URL("https://your-url"), {
requestInit: {
headers: {
Authorization: "Bearer <your-token>",
}
}
})
// Omit the process of creating an MCP Client
await client.connect(transport);
Parameters
Name | Type | Required | Description |
---|---|---|---|
url | URL | Yes | The URL of the MCP Server |
opts | PostClientTransportOptions | No | |
opts.requestInit | RequestInit | No | Parameters carried when initiating a network request. When PostClientTransport sends a network request, it carries the passed parameters, which can be used to pass authentication headers, etc. |
PostServerTransport [deprecated]
[Important] This class is deprecated. Compared to the early official MCP SDK, PostServerTransport
provides more friendly support for stateless MCP Servers. The current official MCP SDK offers Streamable HTTP Transport, which can be used to build both stateless and stateful MCP Servers. For stateless services, we recommend directly using Streamable HTTP Transport.
Post Transport for MCP Server.
In the Function Cloud Hosting scenario, there is no need to directly use PostServerTransport
. It is recommended to directly use CloudbaseMcpServer
, focusing only on the implementation of the MCP Server.
On other platforms/environments, this class can be used as needed to build an MCP Server based on Post Transport.
Import
import { PostServerTransport } from '@cloudbase/mcp/transport/server/post';
new()
Create a PostServerTransport
instance.
const transport = new PostServerTransport();
handleMessage(message: JSONRPCMessage)
Processes JSON RPC messages sent by the client. When the server receives a JSON RPC message sent by the client via an HTTP request, this method must be invoked for processing. This method may return a JSON RPC message, in which case the caller should return the result as the HTTP response body to the client.
// Function Cloud Hosting
export const main = async (context, event) => {
// ...Omit the process of determining the route, HTTP Method, etc.
const transport = new PostServerTransport();
// ...Omit the process of creating an MCP Server instance
server.connect(transport);
// ...Omit the process of determining whether the event is a valid JSON RPC message
return server.handleMessage(event);
}
Parameters
Name | Type | Required | Description |
---|---|---|---|
message | JSONRPCMessage | Yes | Received JSON RPC message |