Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions .eslintrc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
{
"extends": [
"eslint:recommended",
"plugin:@typescript-eslint/recommended"
],
"parser": "@typescript-eslint/parser",
"plugins": ["@typescript-eslint"],
"root": true,
"env": {
"node": true,
"mocha": true
},
"parserOptions": {
"sourceType": "module",
"ecmaVersion": 2020
}
}
7 changes: 7 additions & 0 deletions .prettierrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"semi": true,
"trailingComma": "es5",
"singleQuote": true,
"printWidth": 100,
"tabWidth": 2
}
152 changes: 53 additions & 99 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,132 +1,86 @@
# Solana Model Context Protocol (MCP) Demo
# Solana Transaction Builder MCP

This repository demonstrates a simple implementation of a Model Context Protocol (MCP) server for Solana development.
A Model Context Protocol (MCP) server for building and sending Solana transactions. This tool provides a simple interface for creating, signing, and sending Solana transactions through natural language interactions.

## What is MCP?
## Features

The Model Context Protocol (MCP) is a standardized interface for AI models to interact with tools and resources. This demo showcases a simple MCP server implementation that provides:

1. Basic RPC methods for Solana (getBalance, getAccountInfo, getTransaction)
2. Some helpful prompts for Solana development

## Prerequisites

- Node.js (v16 or higher recommended)
- pnpm package manager (v9.10.0 or compatible)
- Build Solana transactions with simple instructions
- Sign and send transactions
- Query account information
- Support for multiple Solana clusters (mainnet-beta, testnet, devnet)
- Base64 transaction serialization for easy transport

## Installation

Clone this repository and install dependencies:

```bash
git clone https://github.com/solana-foundation/solana-dev-mcp.git
cd solana-dev-mcp
# Clone the repository
git clone https://github.com/yourusername/solana-TxBuilder-mcp.git

# Install dependencies
pnpm install
```

To run this server in the MCP inspector, use:
## Usage

1. Start the MCP server:

```bash
npx @modelcontextprotocol/inspector ts-node index.ts
pnpm start
```

## Getting Started

1. **Explore the code**: The main implementation is in `index.ts`, which sets up an MCP server with simple fetching tools and some prompts.
2. Available Tools:

2. **Modify the server**: You can extend the server by adding more tools, resources, and prompts.
- `buildTransaction`: Build a Solana transaction

3. **Get ideas for extensions**: Check out the [Ideas Extending MCP for Solana Development](#ideas-extending-mcp-for-solana-development) section to get inspiration for new tools and resources to add.
- Parameters:
- instructions: Array of transfer instructions
- cluster: Solana cluster to use
- feePayer: Public key of the fee payer
- signerSecretKey: Base64 encoded secret key for signing

## Example Usage
- `signAndSendTransaction`: Sign and send a Solana transaction

This section explains how to use the Solana MCP server in [Claude](https://modelcontextprotocol.io/quickstart/user).
Follow the same steps to use the Solana MCP server in [Windsurf](https://docs.codeium.com/windsurf/mcp) and [Cursor](https://docs.cursor.com/context/model-context-protocol).
- Parameters:
- transactionBase64: Base64 encoded transaction
- secretKey: Base64 encoded secret key
- cluster: Solana cluster to use

### Generate the configuration file
- `getAccountInfo`: Get account information
- Parameters:
- publicKey: Base58 encoded public key

To use this Solana MCP server, you need to generate a configuration file that Claude can use to connect to the server. Run one of the following commands to generate the configuration file:
## Testing

- `pnpm generate-config` if you have `ts-node` installed globally
- `pnpm build && pnpm generate-config:js` if you don't have `ts-node` installed globally
Run the test suite:

This will print a JSON config with the following content:

If you have `ts-node`:

```json
{
"mcpServers": {
"solana-dev": {
"command": "ts-node",
"args": ["<full-path-to-repo>/index.ts"]
}
}
}
```

If you don't have `ts-node` installed globally:

```json
{
"mcpServers": {
"solana-dev": {
"command": "node",
"args": ["<full-path-to-repo>/dist/index.js"]
}
}
}
```bash
pnpm test
```

## Project Structure

- `index.ts` - Main server implementation
- `package.json` - Project dependencies and metadata
- `tsconfig.json` - TypeScript configuration

## Ideas Extending MCP for Solana Development

This MCP server implementation provides a foundation that you can extend or fork for your own Solana development needs. Here are some ideas to get you started:

### Ideas for Extension

1. **Priority Fee Estimator**: Add a tool that estimates optimal priority fees for Solana transactions based on recent network activity. This could help users optimize transaction costs while ensuring timely processing.

2. **Solana Verify Debugger**: Create a tool that helps debug issues with `solana-verify` by providing more detailed information about the verification process.

3. **Solana Security.txt Inspector**: Build a tool that extracts and displays the security.txt file information for a given Solana program, making it easier to contact the program's maintainers with security concerns.

4. **Squads Helper for Program Deployment**: Create a tool that automates the process of deploying and upgrading Solana programs, making it easier to manage program state across multiple environments.

5. **Anchor-Error Explainer**: Develop a tool that takes an error code and looks up the corresponding human-readable error message from the Anchor error code database.

6. **Enhanced Prompts**: Expand the server's prompt capabilities to provide more context-aware suggestions for Solana development tasks. For example, add prompts for common transaction patterns, account creation, or token operations.

7. **Transaction Builder**: Create tools that help construct complex transactions with multiple instructions, making it easier to interact with various Solana programs.

8. **Custom RPC Endpoints**: Allow configuration of custom RPC endpoints, including support for private RPC providers or local validators.

9. **Program Deployment Helpers**: Create tools that simplify the process of deploying and upgrading Solana programs.
Note: Before running tests, replace the test wallet information in `tests/transaction.test.ts` with your own test wallet.

10. **Account & Transaction Explorer**: Add a tool that takes an account or transaction ID and displays the contents in a human-readable format, similar to an explorer view. This could be useful for inspecting transaction data or account state without needing to manually decode the data.
## Development

11. **Solana, Anchor, and Protocol Documentation**: Add resources that load the Solana, Anchor, and Protocol documentation directly into the MCP editor, providing easy access to relevant information without needing to leave the editor. This could be implemented by fetching the documentation from the respective repositories and serving it as resources from the MCP server.
The project uses TypeScript and follows the MCP server pattern. Key files:

### How to Contribute
- `index.ts`: Main MCP server implementation
- `tests/transaction.test.ts`: Test suite for transaction functionality

If you've built an extension that might be useful to others, consider submitting a pull request to this repository. Make sure to follow these guidelines:
## Contributing

1. Keep your code well-documented
2. Include tests for new functionality
3. Follow the existing code style
4. Update the README with information about your addition
1. Fork the repository
2. Create your feature branch
3. Make your changes
4. Add tests for new functionality
5. Ensure tests pass
6. Submit a pull request

# Security
## License

This is a simple example and should not be used in production.
MCP is a new standard, and lacks proper security measures.
ISC

Please be extremely careful when installing & trying out MCP servers
from unknown developers.
## Dependencies

Please use a sandboxed environment when trying out MCP servers, with no crucial information in it to prevent potential damage.
- @modelcontextprotocol/sdk
- @solana/web3.js
- zod
130 changes: 128 additions & 2 deletions index.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,140 @@
import { McpServer, ResourceTemplate } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import { z } from "zod";
import { Connection, PublicKey, LAMPORTS_PER_SOL, clusterApiUrl } from "@solana/web3.js";
import {
Connection,
PublicKey,
LAMPORTS_PER_SOL,
clusterApiUrl,
Keypair,
Transaction,
SystemProgram
} from "@solana/web3.js";

// Create an MCP server
const server = new McpServer({
name: "Solana RPC Tools",
name: "Sol-TxBuilder-MCP",
version: "1.0.0",
});

// Helper function to get cluster URL
const getClusterUrl = (cluster: string) => {
switch (cluster) {
case "mainnet-beta":
case "testnet":
case "devnet":
return clusterApiUrl(cluster);
default:
throw new Error("Invalid cluster");
}
};

// 1. Build Transaction
server.tool(
"buildTransaction",
"Build a Solana transaction",
{
instructions: z.array(z.object({
type: z.string(),
params: z.object({
from: z.string(),
to: z.string(),
amount: z.number()
})
})),
cluster: z.string(),
feePayer: z.string(),
signerSecretKey: z.string()
},
async ({ instructions, cluster, feePayer, signerSecretKey }) => {
try {
const connection = new Connection(getClusterUrl(cluster));
const transaction = new Transaction();

// Add instructions
for (const inst of instructions) {
if (inst.type === "transfer") {
const instruction = SystemProgram.transfer({
fromPubkey: new PublicKey(inst.params.from),
toPubkey: new PublicKey(inst.params.to),
lamports: LAMPORTS_PER_SOL * inst.params.amount
});
transaction.add(instruction);
}
}

// Set recent blockhash
const { blockhash } = await connection.getLatestBlockhash();
transaction.recentBlockhash = blockhash;
transaction.feePayer = new PublicKey(feePayer);

// Sign the transaction
const signer = Keypair.fromSecretKey(
Buffer.from(signerSecretKey, 'base64')
);
transaction.sign(signer);

return {
content: [{
type: "text",
text: JSON.stringify({
transactionBase64: transaction.serialize().toString('base64')
})
}]
};
} catch (error) {
return {
content: [{
type: "text",
text: `Error: ${(error as Error).message}`
}]
};
}
}
);

// 2. Sign and Send Transaction
server.tool(
"signAndSendTransaction",
"Sign and send a Solana transaction",
{
transactionBase64: z.string(),
secretKey: z.string(),
cluster: z.string()
},
async ({ transactionBase64, secretKey, cluster }) => {
try {
const connection = new Connection(getClusterUrl(cluster));
const transaction = Transaction.from(
Buffer.from(transactionBase64, 'base64')
);

const signer = Keypair.fromSecretKey(
Buffer.from(secretKey, 'base64')
);

transaction.sign(signer);
const signature = await connection.sendRawTransaction(
transaction.serialize()
);

return {
content: [{
type: "text",
text: JSON.stringify({ signature })
}]
};
} catch (error) {
return {
content: [{
type: "text",
text: `Error: ${(error as Error).message}`
}]
};
}
}
);

// Initialize Solana connection
const connection = new Connection(clusterApiUrl("mainnet-beta"), "confirmed");

Expand Down
15 changes: 14 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
"scripts": {
"build": "tsc",
"start": "ts-node index.ts",
"test": "mocha --require ts-node/register tests/**/*.test.ts",
"generate-config": "echo '{\"mcpServers\":{\"solana-dev\":{\"command\":\"ts-node\",\"args\":[\"'$(pwd)'/index.ts\"]}}}'",
"generate-config:js": "echo '{\"mcpServers\":{\"solana-dev\":{\"command\":\"node\",\"args\":[\"'$(pwd)'/dist/index.js\"]}}}'"
},
Expand All @@ -19,6 +20,18 @@
"zod": "^3.24.2"
},
"devDependencies": {
"@types/node": "^22.13.10"
"@types/chai": "5.2.0",
"@types/mocha": "10.0.10",
"@types/node": "^22.13.10",
"@typescript-eslint/eslint-plugin": "8.26.1",
"@typescript-eslint/parser": "8.26.1",
"chai": "5.2.0",
"eslint": "9.22.0",
"eslint-config-prettier": "10.1.1",
"mocha": "11.1.0",
"prettier": "3.5.3",
"ts-mocha": "11.1.0",
"ts-node": "10.9.2",
"typescript": "5.8.2"
}
}
Loading