1+ import { Server } from "@modelcontextprotocol/sdk/server/index.js" ;
2+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js" ;
3+ import {
4+ CallToolRequestSchema ,
5+ ListToolsRequestSchema ,
6+ } from "@modelcontextprotocol/sdk/types.js" ;
7+ import { PolkadotAgentKit , getMcpTools } from "@polkadot-agent-kit/sdk" ;
8+
9+
10+ function validateEnvironment ( ) : void {
11+ const requiredVars = [ "PRIVATE_KEY" ] ;
12+ const missingVars = requiredVars . filter ( varName => ! process . env [ varName ] ) ;
13+
14+ if ( missingVars . length > 0 ) {
15+ const errorMessage = `Missing required environment variables: ${ missingVars . join ( ', ' ) } ` ;
16+ throw new Error ( errorMessage ) ;
17+ }
18+ }
19+
20+
21+
22+ async function initializeServer ( ) {
23+ try {
24+ // Create MCP server
25+ const server = new Server (
26+ {
27+ name : "polkadot-agent-kit" ,
28+ version : "1.0.0" ,
29+ } ,
30+ {
31+ capabilities : {
32+ tools : { } ,
33+ } ,
34+ }
35+ ) ;
36+
37+ // Initialize the agent kit
38+ const polkadotAgentKit = new PolkadotAgentKit ( {
39+ privateKey : process . env . PRIVATE_KEY ,
40+
41+ } ) ;
42+
43+ await polkadotAgentKit . initializeApi ( ) ;
44+
45+ // Get MCP tools
46+ const { tools, toolHandler } = await getMcpTools ( polkadotAgentKit ) ;
47+
48+ // Handle tool listing
49+ server . setRequestHandler ( ListToolsRequestSchema , async ( ) => {
50+ return { tools } ;
51+ } ) ;
52+
53+ // Handle tool calls
54+ server . setRequestHandler ( CallToolRequestSchema , async ( request ) => {
55+ return await toolHandler ( request . params . name , request . params . arguments ) ;
56+ } ) ;
57+
58+ return server ;
59+ } catch ( error ) {
60+ console . error ( "Failed to initialize server:" , error ) ;
61+ throw error ;
62+ }
63+ }
64+
65+ /**
66+ * Main function to run the Polkadot MCP server
67+ */
68+ async function main ( ) {
69+ try {
70+ validateEnvironment ( ) ;
71+ const server = await initializeServer ( ) ;
72+ const transport = new StdioServerTransport ( ) ;
73+ await server . connect ( transport ) ;
74+ console . error ( "Polkadot Agent Kit MCP Server running on stdio" ) ;
75+ } catch ( error ) {
76+ console . error ( "Fatal error:" , error ) ;
77+ process . exit ( 1 ) ;
78+ }
79+ }
80+
81+ if ( require . main === module ) {
82+ main ( ) . catch ( error => {
83+ console . error ( "Fatal error in main():" , error ) ;
84+ process . exit ( 1 ) ;
85+ } ) ;
86+ }
0 commit comments