Skip to content

Instantly share code, notes, and snippets.

@thearyanag
Created May 4, 2025 09:44
Show Gist options
  • Select an option

  • Save thearyanag/ac6a92d10f40ab90d55f5fac489a15d7 to your computer and use it in GitHub Desktop.

Select an option

Save thearyanag/ac6a92d10f40ab90d55f5fac489a15d7 to your computer and use it in GitHub Desktop.
Solana Agent Kit with Cloudflare Workers
import { McpAgent } from "agents/mcp";
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { SolanaAgentKit, KeypairWallet } from "solana-agent-kit";
import { Keypair } from "@solana/web3.js";
import { zodToMCPShape } from "@solana-agent-kit/adapter-mcp";
import TokenPlugin from "@solana-agent-kit/plugin-token";
import bs58 from "bs58";
interface Env {
SOLANA_PRIVATE_KEY: string;
RPC_URL: string;
}
export class MyMCP extends McpAgent {
server = new McpServer({
name: "SendAI Solana Agent",
version: "1.0.0",
});
env = this.env as Env;
private keypair = Keypair.fromSecretKey(bs58.decode(this.env.SOLANA_PRIVATE_KEY));
private wallet = new KeypairWallet(this.keypair, this.env.RPC_URL!);
private solanaAgent = new SolanaAgentKit(this.wallet, this.env.RPC_URL!, {});
async init() {
this.solanaAgent.use(TokenPlugin);
const actions = this.solanaAgent.actions;
for (const action of actions) {
const { result } = zodToMCPShape(action.schema);
this.server.tool(action.name, action.description, result, async (params) => {
try {
const result = await action.handler(this.solanaAgent, params);
return {
content: [
{
type: "text",
text: JSON.stringify(result, null, 2),
},
],
};
} catch (error) {
console.error("error", error);
// Handle errors in MCP format
return {
isError: true,
content: [
{
type: "text",
text:
error instanceof Error
? error.message
: "Unknown error occurred",
},
],
};
}
});
}
}
}
export default {
fetch(request: Request, env: Env, ctx: ExecutionContext) {
const url = new URL(request.url);
if (url.pathname === "/sse" || url.pathname === "/sse/message") {
// @ts-ignore
return MyMCP.serveSSE("/sse").fetch(request, env, ctx);
}
if (url.pathname === "/mcp") {
// @ts-ignore
return MyMCP.serve("/mcp").fetch(request, env, ctx);
}
return new Response("Not found", { status: 404 });
},
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment