story-build
Version:
MCP library for AI-assisted IP registration and licensing on Story Protocol
1,294 lines (1,281 loc) • 129 kB
JavaScript
#!/usr/bin/env node
// src/config.ts
import { aeneid, mainnet, StoryClient } from "@story-protocol/core-sdk";
import { createPublicClient, createWalletClient, http } from "viem";
import { privateKeyToAccount } from "viem/accounts";
import dotenv from "dotenv";
dotenv.config();
var getArgs = () => process.argv.reduce((args, arg) => {
if (arg.slice(0, 2) === "--") {
const longArg = arg.split("=");
const longArgFlag = longArg[0].slice(2);
const longArgValue = longArg.length > 1 ? longArg[1] : true;
args[longArgFlag] = longArgValue;
} else if (arg[0] === "-") {
const flags = arg.slice(1).split("");
flags.forEach((flag) => {
args[flag] = true;
});
}
return args;
}, {});
var networkConfigs = {
aeneid: {
rpcProviderUrl: "https://aeneid.storyrpc.io",
blockExplorer: "https://aeneid.storyscan.io",
protocolExplorer: "https://aeneid.explorer.story.foundation",
defaultNFTContractAddress: "0x937bef10ba6fb941ed84b8d249abc76031429a9a",
defaultSPGNFTContractAddress: "0xc32A8a0FF3beDDDa58393d022aF433e78739FAbc",
chain: aeneid
},
mainnet: {
rpcProviderUrl: "https://mainnet.storyrpc.io",
blockExplorer: "https://storyscan.io",
protocolExplorer: "https://explorer.story.foundation",
defaultNFTContractAddress: null,
defaultSPGNFTContractAddress: "0x98971c660ac20880b60F86Cc3113eBd979eb3aAE",
chain: mainnet
}
};
var getNetwork = () => {
const args = getArgs();
const network2 = args?.story_network || process.env.STORY_NETWORK || "aeneid";
if (network2 && !(network2 in networkConfigs)) {
throw new Error(`Invalid network: ${network2}. Must be one of: ${Object.keys(networkConfigs).join(", ")}`);
}
return network2 || "aeneid";
};
var getAccount = () => {
const args = getArgs();
const hasPrivateKey = !!(args?.wallet_private_key || process.env.WALLET_PRIVATE_KEY);
if (!hasPrivateKey) {
throw new Error("WALLET_PRIVATE_KEY environment variable is required");
}
return privateKeyToAccount(`0x${args?.wallet_private_key || process.env.WALLET_PRIVATE_KEY}`);
};
var network = getNetwork();
var networkInfo = {
...networkConfigs[network],
rpcProviderUrl: networkConfigs[network].rpcProviderUrl
};
var account = getAccount();
var config = {
account,
transport: http(networkInfo.rpcProviderUrl),
chainId: network
};
var client = StoryClient.newClient(config);
var baseConfig = {
chain: networkInfo.chain,
transport: http(networkInfo.rpcProviderUrl)
};
var publicClient = createPublicClient(baseConfig);
var walletClient = createWalletClient({
...baseConfig,
account
});
function validateEnvironment() {
try {
getAccount();
getNetwork();
console.error(`\u2705 Story Protocol environment configuration valid (${network})`);
console.error(`\u{1F4CD} RPC URL: ${networkInfo.rpcProviderUrl}`);
console.error(`\u{1F4CD} Account: ${account.address}`);
} catch (error) {
console.error("\u274C Invalid environment configuration:", error);
throw error;
}
}
// src/index.ts
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
// src/mcp/wallet/get_wallet_info_tool.ts
var GetWalletInfoTool = {
name: "story_get_wallet_info",
description: "Get wallet address and basic account information",
schema: {},
handler: async (agent, input) => {
try {
await agent.connect();
const balance = await agent.publicClient.getBalance({
address: agent.account.address
});
const balanceInETH = Number(balance) / 1e18;
return {
status: "success",
message: "\u2705 Wallet information retrieved successfully",
wallet_details: {
address: agent.account.address,
network: agent.network,
balance: `${balanceInETH.toFixed(6)} IP`,
balance_in_wei: balance.toString(),
chain_id: await agent.publicClient.getChainId(),
block_explorer: agent.networkInfo.blockExplorer,
protocol_explorer: agent.networkInfo.protocolExplorer
},
account_status: {
activated: true,
minimum_balance_required: "0.01 IP",
can_register_ip: balanceInETH >= 0.01,
ready_for_operations: balanceInETH >= 1e-3
},
recommendations: balanceInETH < 0.01 ? [
"\u26A0\uFE0F Low IP balance detected",
"Fund wallet with at least 0.01 IP for IP registration",
"Gas fees required for all Story Protocol operations",
`Current balance: ${balanceInETH.toFixed(6)} IP`
] : [
"\u2705 Wallet has sufficient balance for operations",
"Ready to register IP assets",
"Ready to create license terms and mint tokens"
]
};
} catch (error) {
throw new Error(`Failed to get wallet info: ${error.message}`);
} finally {
await agent.disconnect();
}
}
};
// src/mcp/wallet/get_account_balances_tool.ts
import { z } from "zod";
import { formatEther } from "viem";
import { WIP_TOKEN_ADDRESS } from "@story-protocol/core-sdk";
var GetAccountBalancesTool = {
name: "story_get_account_balances",
description: "Get all token balances including IP, WIP tokens, and license tokens",
schema: {
account_address: z.string().regex(/^0x[0-9a-fA-F]{40}$/).optional().describe("Ethereum address to check (optional, defaults to wallet address)")
},
handler: async (agent, input) => {
try {
await agent.connect();
const targetAddress = input.account_address || agent.account.address;
const ethBalance = await agent.publicClient.getBalance({
address: targetAddress
});
let wipBalance = BigInt(0);
try {
wipBalance = await agent.publicClient.readContract({
address: WIP_TOKEN_ADDRESS,
abi: [
{
name: "balanceOf",
type: "function",
stateMutability: "view",
inputs: [{ name: "account", type: "address" }],
outputs: [{ name: "", type: "uint256" }]
}
],
functionName: "balanceOf",
args: [targetAddress]
});
} catch (error) {
console.error("Error fetching WIP balance:", error);
}
return {
status: "success",
message: `\u2705 Account balances retrieved for ${targetAddress}`,
account_info: {
address: targetAddress,
network: agent.network,
is_own_wallet: targetAddress.toLowerCase() === agent.account.address.toLowerCase()
},
native_balance: {
symbol: "IP",
balance: formatEther(ethBalance),
balance_wei: ethBalance.toString(),
usd_value: "N/A"
// Could integrate price feeds later
},
story_protocol_tokens: {
wip: {
symbol: "WIP",
name: "Wrapped IP Token",
balance: formatEther(wipBalance),
balance_wei: wipBalance.toString(),
contract_address: WIP_TOKEN_ADDRESS,
purpose: "Used for licensing fees and royalty payments"
}
},
portfolio_summary: {
total_ip_balance: formatEther(ethBalance),
total_wip_balance: formatEther(wipBalance),
can_pay_gas: Number(formatEther(ethBalance)) > 1e-3,
can_pay_licensing_fees: wipBalance > 0,
ready_for_ip_operations: Number(formatEther(ethBalance)) > 1e-3
},
next_steps: Number(formatEther(ethBalance)) < 1e-3 ? [
"\u{1F50B} Fund wallet with ETH for gas fees",
"\u{1F48E} Acquire WIP tokens for licensing operations",
"\u{1F3A8} Ready to register IP assets once funded"
] : [
"\u2705 Sufficient ETH for gas fees",
"\u{1F3A8} Ready to register IP assets",
"\u{1F3AB} Ready to mint and purchase licenses",
wipBalance === BigInt(0) ? "\u{1F4A1} Consider acquiring WIP tokens for licensing" : "\u{1F48E} WIP tokens available for licensing"
]
};
} catch (error) {
throw new Error(`Failed to get account balances: ${error.message}`);
} finally {
await agent.disconnect();
}
}
};
// src/mcp/wallet/send_eth_tool.ts
import { z as z2 } from "zod";
import { parseEther } from "viem";
var SendETHTool = {
name: "story_send_native_ip",
description: "Send native IP token to another address for gas fees or payments",
schema: {
destination: z2.string().regex(/^0x[0-9a-fA-F]{40}$/).describe("Recipient's Ethereum address"),
amount: z2.number().positive().describe("Amount of IP to send"),
memo: z2.string().optional().describe("Optional memo for the transaction")
},
handler: async (agent, input) => {
try {
await agent.connect();
const destination = input.destination;
const amount = parseEther(input.amount.toString());
const balance = await agent.publicClient.getBalance({
address: agent.account.address
});
if (balance < amount) {
throw new Error(`Insufficient balance. Available: ${Number(balance) / 1e18} IP, Required: ${input.amount} IP`);
}
let gasEstimate;
try {
gasEstimate = await agent.publicClient.estimateGas({
account: agent.account.address,
to: destination,
value: amount
});
} catch (error) {
throw new Error(`Transaction simulation failed: ${error.message}. Check recipient address and amount.`);
}
const gasPrice = await agent.publicClient.getGasPrice();
const gasCost = gasEstimate * gasPrice;
if (balance < amount + gasCost) {
throw new Error(`Insufficient balance for transaction + gas. Total needed: ${Number(amount + gasCost) / 1e18} IP`);
}
console.error(`\u2705 Native IP transfer simulation successful. Gas estimate: ${gasEstimate.toString()}`);
const txHash = await agent.walletClient.sendTransaction({
account: agent.account,
to: destination,
value: amount,
gas: gasEstimate
});
const receipt = await agent.publicClient.waitForTransactionReceipt({
hash: txHash,
confirmations: 1
});
return {
status: "success",
message: `\u2705 Successfully sent ${input.amount} IP to ${destination}`,
transaction_details: {
transaction_hash: txHash,
from: agent.account.address,
to: destination,
amount: `${input.amount} IP`,
amount_wei: amount.toString(),
gas_used: receipt.gasUsed.toString(),
gas_price: gasPrice.toString(),
total_cost: `${Number(amount + receipt.gasUsed * gasPrice) / 1e18} IP`,
block_number: receipt.blockNumber.toString(),
confirmations: 1,
memo: input.memo || "N/A"
},
network_info: {
network: agent.network,
explorer_url: `${agent.networkInfo.blockExplorer}/tx/${txHash}`
},
next_steps: [
"\u2705 Transaction confirmed on blockchain",
"\u{1F50D} View transaction details on block explorer",
"\u{1F4B0} Recipient can now use IP for Story Protocol operations"
]
};
} catch (error) {
throw new Error(`Failed to send IP: ${error.message}`);
} finally {
await agent.disconnect();
}
}
};
// src/mcp/wallet/send_token_tool.ts
import { z as z3 } from "zod";
import { parseEther as parseEther2, formatEther as formatEther2 } from "viem";
import { WIP_TOKEN_ADDRESS as WIP_TOKEN_ADDRESS2 } from "@story-protocol/core-sdk";
var SendTokenTool = {
name: "story_send_token",
description: "Send Story Protocol tokens (WIP, or custom tokens) to another address",
schema: {
token_address: z3.string().regex(/^0x[0-9a-fA-F]{40}$/).describe("Token contract address (use 'WIP' for WIP token shortcut)"),
destination: z3.string().regex(/^0x[0-9a-fA-F]{40}$/).describe("Recipient's Ethereum address"),
amount: z3.number().positive().describe("Amount of tokens to send"),
memo: z3.string().optional().describe("Optional memo for the transaction")
},
handler: async (agent, input) => {
try {
await agent.connect();
const destination = input.destination;
let tokenAddress = input.token_address;
if (input.token_address === "WIP") {
tokenAddress = WIP_TOKEN_ADDRESS2;
}
const amount = parseEther2(input.amount.toString());
const erc20Abi = [
{
name: "transfer",
type: "function",
stateMutability: "nonpayable",
inputs: [
{ name: "to", type: "address" },
{ name: "amount", type: "uint256" }
],
outputs: [{ name: "", type: "bool" }]
},
{
name: "balanceOf",
type: "function",
stateMutability: "view",
inputs: [{ name: "account", type: "address" }],
outputs: [{ name: "", type: "uint256" }]
},
{
name: "symbol",
type: "function",
stateMutability: "view",
inputs: [],
outputs: [{ name: "", type: "string" }]
},
{
name: "decimals",
type: "function",
stateMutability: "view",
inputs: [],
outputs: [{ name: "", type: "uint8" }]
}
];
const [balance, symbol, decimals] = await Promise.all([
agent.publicClient.readContract({
address: tokenAddress,
abi: erc20Abi,
functionName: "balanceOf",
args: [agent.account.address]
}),
agent.publicClient.readContract({
address: tokenAddress,
abi: erc20Abi,
functionName: "symbol"
}),
agent.publicClient.readContract({
address: tokenAddress,
abi: erc20Abi,
functionName: "decimals"
})
]);
if (balance < amount) {
throw new Error(`Insufficient ${symbol} balance. Available: ${formatEther2(balance)}, Required: ${input.amount}`);
}
const { request, result } = await agent.publicClient.simulateContract({
address: tokenAddress,
abi: erc20Abi,
functionName: "transfer",
args: [destination, amount],
account: agent.account.address
});
console.error(`\u2705 Transfer simulation successful. Proceeding with transaction...`);
const txHash = await agent.walletClient.writeContract(request);
const receipt = await agent.publicClient.waitForTransactionReceipt({
hash: txHash,
confirmations: 1
});
return {
status: "success",
message: `\u2705 Successfully sent ${input.amount} ${symbol} to ${destination}`,
transaction_details: {
transaction_hash: txHash,
from: agent.account.address,
to: destination,
token_address: tokenAddress,
token_symbol: symbol,
amount: `${input.amount} ${symbol}`,
amount_wei: amount.toString(),
decimals,
gas_used: receipt.gasUsed.toString(),
block_number: receipt.blockNumber.toString(),
confirmations: 1,
memo: input.memo || "N/A"
},
token_info: {
contract_address: tokenAddress,
symbol,
decimals,
is_story_protocol_token: tokenAddress === WIP_TOKEN_ADDRESS2
},
network_info: {
network: agent.network,
explorer_url: `${agent.networkInfo.blockExplorer}/tx/${txHash}`
},
next_steps: [
"\u2705 Token transfer confirmed on blockchain",
"\u{1F50D} View transaction details on block explorer",
`\u{1F48E} Recipient can now use ${symbol} tokens for Story Protocol operations`
]
};
} catch (error) {
throw new Error(`Failed to send tokens: ${error.message}`);
} finally {
await agent.disconnect();
}
}
};
// src/mcp/wallet/approve_token_tool.ts
import { z as z4 } from "zod";
import { parseEther as parseEther3, formatEther as formatEther3, maxUint256 } from "viem";
import { WIP_TOKEN_ADDRESS as WIP_TOKEN_ADDRESS3 } from "@story-protocol/core-sdk";
var ApproveTokenTool = {
name: "story_approve_token",
description: "Approve Story Protocol contracts to spend your tokens (required for licensing operations)",
schema: {
token_address: z4.string().regex(/^0x[0-9a-fA-F]{40}$/).describe("Token contract address (use 'WIP' for WIP token shortcut)"),
spender: z4.string().regex(/^0x[0-9a-fA-F]{40}$/).describe("Contract address to approve (Story Protocol contracts)"),
amount: z4.number().positive().optional().describe("Amount to approve (optional, defaults to unlimited)"),
unlimited: z4.boolean().default(true).describe("Set unlimited approval (recommended for convenience)")
},
handler: async (agent, input) => {
try {
await agent.connect();
let tokenAddress = input.token_address;
const spender = input.spender;
if (input.token_address === "WIP") {
tokenAddress = WIP_TOKEN_ADDRESS3;
}
const amount = input.unlimited || !input.amount ? maxUint256 : parseEther3(input.amount.toString());
const erc20Abi = [
{
name: "approve",
type: "function",
stateMutability: "nonpayable",
inputs: [
{ name: "spender", type: "address" },
{ name: "amount", type: "uint256" }
],
outputs: [{ name: "", type: "bool" }]
},
{
name: "allowance",
type: "function",
stateMutability: "view",
inputs: [
{ name: "owner", type: "address" },
{ name: "spender", type: "address" }
],
outputs: [{ name: "", type: "uint256" }]
},
{
name: "symbol",
type: "function",
stateMutability: "view",
inputs: [],
outputs: [{ name: "", type: "string" }]
},
{
name: "balanceOf",
type: "function",
stateMutability: "view",
inputs: [{ name: "account", type: "address" }],
outputs: [{ name: "", type: "uint256" }]
}
];
const [currentAllowance, symbol, balance] = await Promise.all([
agent.publicClient.readContract({
address: tokenAddress,
abi: erc20Abi,
functionName: "allowance",
args: [agent.account.address, spender]
}),
agent.publicClient.readContract({
address: tokenAddress,
abi: erc20Abi,
functionName: "symbol"
}),
agent.publicClient.readContract({
address: tokenAddress,
abi: erc20Abi,
functionName: "balanceOf",
args: [agent.account.address]
})
]);
if (currentAllowance >= amount && amount !== maxUint256) {
return {
status: "success",
message: `\u2705 Sufficient approval already exists for ${symbol}`,
approval_details: {
token_address: tokenAddress,
token_symbol: symbol,
spender,
current_allowance: input.unlimited ? "Unlimited" : formatEther3(currentAllowance),
requested_amount: input.unlimited ? "Unlimited" : input.amount?.toString(),
approval_needed: false
},
wallet_info: {
balance: formatEther3(balance),
address: agent.account.address
},
next_steps: [
"\u2705 Approval already sufficient",
"\u{1F3A8} Ready to proceed with Story Protocol operations",
"\u{1F4A1} No additional transaction needed"
]
};
}
const { request, result } = await agent.publicClient.simulateContract({
address: tokenAddress,
abi: erc20Abi,
functionName: "approve",
args: [spender, amount],
account: agent.account.address
});
console.error(`\u2705 Approval simulation successful. Proceeding with transaction...`);
const txHash = await agent.walletClient.writeContract(request);
const receipt = await agent.publicClient.waitForTransactionReceipt({
hash: txHash,
confirmations: 1
});
const newAllowance = await agent.publicClient.readContract({
address: tokenAddress,
abi: erc20Abi,
functionName: "allowance",
args: [agent.account.address, spender]
});
return {
status: "success",
message: `\u2705 Successfully approved ${symbol} spending for Story Protocol contract`,
transaction_details: {
transaction_hash: txHash,
from: agent.account.address,
token_address: tokenAddress,
token_symbol: symbol,
spender,
approved_amount: input.unlimited ? "Unlimited" : input.amount?.toString(),
gas_used: receipt.gasUsed.toString(),
block_number: receipt.blockNumber.toString(),
confirmations: 1
},
approval_details: {
previous_allowance: formatEther3(currentAllowance),
new_allowance: amount === maxUint256 ? "Unlimited" : formatEther3(newAllowance),
is_unlimited: amount === maxUint256,
spender_contract: spender
},
wallet_info: {
balance: formatEther3(balance),
address: agent.account.address
},
network_info: {
network: agent.network,
explorer_url: `${agent.networkInfo.blockExplorer}/tx/${txHash}`
},
next_steps: [
"\u2705 Token approval confirmed on blockchain",
"\u{1F3A8} Ready to register IP assets and mint licenses",
"\u{1F48E} Story Protocol contracts can now spend your tokens",
"\u{1F50D} View transaction details on block explorer"
]
};
} catch (error) {
throw new Error(`Failed to approve tokens: ${error.message}`);
} finally {
await agent.disconnect();
}
}
};
// src/mcp/wallet/check_allowance_tool.ts
import { z as z5 } from "zod";
import { formatEther as formatEther4 } from "viem";
import { WIP_TOKEN_ADDRESS as WIP_TOKEN_ADDRESS4 } from "@story-protocol/core-sdk";
var CheckAllowanceTool = {
name: "story_check_allowance",
description: "Check token allowance for Story Protocol contracts and other spenders",
schema: {
token_address: z5.string().regex(/^0x[0-9a-fA-F]{40}$/).describe("Token contract address (use 'WIP' for WIP token shortcut)"),
owner: z5.string().regex(/^0x[0-9a-fA-F]{40}$/).optional().describe("Token owner address (optional, defaults to wallet address)"),
spender: z5.string().regex(/^0x[0-9a-fA-F]{40}$/).describe("Spender contract address to check allowance for")
},
handler: async (agent, input) => {
try {
await agent.connect();
let tokenAddress = input.token_address;
const owner = input.owner || agent.account.address;
const spender = input.spender;
if (input.token_address === "WIP") {
tokenAddress = WIP_TOKEN_ADDRESS4;
}
const erc20Abi = [
{
name: "allowance",
type: "function",
stateMutability: "view",
inputs: [
{ name: "owner", type: "address" },
{ name: "spender", type: "address" }
],
outputs: [{ name: "", type: "uint256" }]
},
{
name: "balanceOf",
type: "function",
stateMutability: "view",
inputs: [{ name: "account", type: "address" }],
outputs: [{ name: "", type: "uint256" }]
},
{
name: "symbol",
type: "function",
stateMutability: "view",
inputs: [],
outputs: [{ name: "", type: "string" }]
},
{
name: "decimals",
type: "function",
stateMutability: "view",
inputs: [],
outputs: [{ name: "", type: "uint8" }]
},
{
name: "name",
type: "function",
stateMutability: "view",
inputs: [],
outputs: [{ name: "", type: "string" }]
}
];
const [allowance, balance, symbol, decimals, name] = await Promise.all([
agent.publicClient.readContract({
address: tokenAddress,
abi: erc20Abi,
functionName: "allowance",
args: [owner, spender]
}),
agent.publicClient.readContract({
address: tokenAddress,
abi: erc20Abi,
functionName: "balanceOf",
args: [owner]
}),
agent.publicClient.readContract({
address: tokenAddress,
abi: erc20Abi,
functionName: "symbol"
}),
agent.publicClient.readContract({
address: tokenAddress,
abi: erc20Abi,
functionName: "decimals"
}),
agent.publicClient.readContract({
address: tokenAddress,
abi: erc20Abi,
functionName: "name"
})
]);
const maxUint2562 = BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");
const isUnlimited = allowance >= maxUint2562 / BigInt(2);
const allowanceFormatted = isUnlimited ? "Unlimited" : formatEther4(allowance);
const balanceFormatted = formatEther4(balance);
const canSpendBalance = allowance >= balance;
const needsApproval = allowance === BigInt(0);
const getRecommendations = () => {
if (needsApproval) {
return [
"\u26A0\uFE0F No allowance set - approval required",
`Use story_approve_token to approve ${symbol} spending`,
"Recommend setting unlimited approval for convenience"
];
} else if (!canSpendBalance && !isUnlimited) {
return [
"\u26A0\uFE0F Allowance is less than current balance",
`Current allowance: ${allowanceFormatted} ${symbol}`,
`Current balance: ${balanceFormatted} ${symbol}`,
"Consider increasing allowance for full balance access"
];
} else if (isUnlimited) {
return [
"\u2705 Unlimited allowance set",
"No further approvals needed for this token",
"Ready for all Story Protocol operations"
];
} else {
return [
"\u2705 Sufficient allowance for current balance",
`Can spend up to ${allowanceFormatted} ${symbol}`,
"Ready for Story Protocol operations"
];
}
};
return {
status: "success",
message: `\u2705 Allowance checked for ${symbol} token`,
allowance_details: {
token_address: tokenAddress,
token_name: name,
token_symbol: symbol,
token_decimals: decimals,
owner,
spender,
allowance: allowanceFormatted,
allowance_wei: allowance.toString(),
is_unlimited: isUnlimited,
is_zero: allowance === BigInt(0)
},
balance_comparison: {
owner_balance: balanceFormatted,
owner_balance_wei: balance.toString(),
can_spend_full_balance: canSpendBalance,
allowance_vs_balance: allowance >= balance ? "sufficient" : "insufficient"
},
contract_info: {
is_story_protocol_token: tokenAddress === WIP_TOKEN_ADDRESS4,
spender_contract: spender,
is_own_wallet: owner.toLowerCase() === agent.account.address.toLowerCase()
},
operational_status: {
needs_approval: needsApproval,
ready_for_operations: !needsApproval,
can_spend_tokens: allowance > 0,
approval_sufficient: canSpendBalance || isUnlimited
},
network_info: {
network: agent.network,
block_explorer: agent.networkInfo.blockExplorer,
token_explorer_url: `${agent.networkInfo.blockExplorer}/token/${tokenAddress}`,
approval_explorer_url: `${agent.networkInfo.blockExplorer}/token/${tokenAddress}?a=${owner}`
},
recommendations: getRecommendations(),
next_steps: needsApproval ? [
`\u{1F527} Run: story_approve_token with token_address=${symbol === "WIP" ? "WIP" : tokenAddress}`,
`\u{1F4C4} Specify spender=${spender}`,
"\u{1F4A1} Consider unlimited approval for convenience",
"\u{1F3A8} Then proceed with Story Protocol operations"
] : [
"\u2705 Allowance is properly configured",
"\u{1F3A8} Ready to proceed with Story Protocol operations",
`\u{1F48E} Can spend ${canSpendBalance ? "full balance" : "partial balance"} of ${symbol}`,
"\u{1F50D} View token details on block explorer"
]
};
} catch (error) {
throw new Error(`Failed to check allowance: ${error.message}`);
} finally {
await agent.disconnect();
}
}
};
// src/mcp/wallet/get_token_info_tool.ts
import { z as z6 } from "zod";
import { formatEther as formatEther5 } from "viem";
import { WIP_TOKEN_ADDRESS as WIP_TOKEN_ADDRESS5 } from "@story-protocol/core-sdk";
var GetTokenInfoTool = {
name: "story_get_token_info",
description: "Get comprehensive information about ERC20 tokens including metadata and user balances",
schema: {
token_address: z6.string().regex(/^0x[0-9a-fA-F]{40}$/).describe("Token contract address (use 'WIP' for WIP token shortcut)"),
account_address: z6.string().regex(/^0x[0-9a-fA-F]{40}$/).optional().describe("Address to check balance for (optional, defaults to wallet address)")
},
handler: async (agent, input) => {
try {
await agent.connect();
let tokenAddress = input.token_address;
const accountAddress = input.account_address || agent.account.address;
if (input.token_address === "WIP") {
tokenAddress = WIP_TOKEN_ADDRESS5;
}
const erc20Abi = [
{
name: "name",
type: "function",
stateMutability: "view",
inputs: [],
outputs: [{ name: "", type: "string" }]
},
{
name: "symbol",
type: "function",
stateMutability: "view",
inputs: [],
outputs: [{ name: "", type: "string" }]
},
{
name: "decimals",
type: "function",
stateMutability: "view",
inputs: [],
outputs: [{ name: "", type: "uint8" }]
},
{
name: "totalSupply",
type: "function",
stateMutability: "view",
inputs: [],
outputs: [{ name: "", type: "uint256" }]
},
{
name: "balanceOf",
type: "function",
stateMutability: "view",
inputs: [{ name: "account", type: "address" }],
outputs: [{ name: "", type: "uint256" }]
}
];
const [name, symbol, decimals, totalSupply, balance] = await Promise.all([
agent.publicClient.readContract({
address: tokenAddress,
abi: erc20Abi,
functionName: "name"
}),
agent.publicClient.readContract({
address: tokenAddress,
abi: erc20Abi,
functionName: "symbol"
}),
agent.publicClient.readContract({
address: tokenAddress,
abi: erc20Abi,
functionName: "decimals"
}),
agent.publicClient.readContract({
address: tokenAddress,
abi: erc20Abi,
functionName: "totalSupply"
}),
agent.publicClient.readContract({
address: tokenAddress,
abi: erc20Abi,
functionName: "balanceOf",
args: [accountAddress]
})
]);
const bytecode = await agent.publicClient.getBytecode({
address: tokenAddress
});
const isContract = !!(bytecode && bytecode !== "0x");
const totalSupplyFormatted = formatEther5(totalSupply);
const balanceFormatted = formatEther5(balance);
const balancePercentage = totalSupply > 0 ? Number(balance) / Number(totalSupply) * 100 : 0;
const getTokenInfo = () => {
if (tokenAddress === WIP_TOKEN_ADDRESS5) {
return {
type: "story_protocol_token",
category: "wrapped_token",
purpose: "Used for licensing fees and royalty payments on Story Protocol",
official: true
};
} else {
return {
type: "erc20_token",
category: "custom",
purpose: "Custom ERC20 token - verify legitimacy before use",
official: false
};
}
};
const tokenInfo = getTokenInfo();
return {
status: "success",
message: `\u2705 Token information retrieved for ${symbol}`,
token_metadata: {
contract_address: tokenAddress,
name,
symbol,
decimals,
total_supply: totalSupplyFormatted,
total_supply_wei: totalSupply.toString(),
is_contract: isContract,
...tokenInfo
},
account_balance: {
address: accountAddress,
balance: balanceFormatted,
balance_wei: balance.toString(),
percentage_of_supply: balancePercentage.toFixed(6) + "%",
is_holder: balance > 0,
is_own_wallet: accountAddress.toLowerCase() === agent.account.address.toLowerCase()
},
supply_analysis: {
total_supply_formatted: totalSupplyFormatted,
user_balance_formatted: balanceFormatted,
supply_concentration: balancePercentage > 1 ? "significant_holder" : balancePercentage > 0.1 ? "moderate_holder" : balancePercentage > 0 ? "small_holder" : "non_holder"
},
story_protocol_integration: {
is_story_token: tokenInfo.official,
can_use_for_licensing: tokenAddress === WIP_TOKEN_ADDRESS5,
can_use_for_governance: false,
purpose: tokenInfo.purpose,
recommended_for_ip_operations: tokenInfo.official
},
network_info: {
network: agent.network,
block_explorer: agent.networkInfo.blockExplorer,
token_explorer_url: `${agent.networkInfo.blockExplorer}/token/${tokenAddress}`,
account_explorer_url: `${agent.networkInfo.blockExplorer}/token/${tokenAddress}?a=${accountAddress}`
},
operational_status: {
has_balance: balance > 0,
can_transfer: balance > 0,
ready_for_story_operations: tokenInfo.official && balance > 0,
needs_acquisition: balance === BigInt(0) && tokenInfo.official
},
next_steps: balance === BigInt(0) ? [
`\u{1F4B0} Acquire ${symbol} tokens to use for Story Protocol`,
tokenInfo.official ? `\u{1F3AF} ${symbol} is required for licensing operations` : "\u26A0\uFE0F Verify token legitimacy before acquiring",
`\u{1F50D} View token details on ${agent.networkInfo.blockExplorer}`,
"\u{1F4A1} Use story_send_token to receive tokens from others"
] : [
`\u2705 You have ${balanceFormatted} ${symbol} tokens`,
tokenInfo.official ? "\u{1F3A8} Ready for Story Protocol operations" : "\u26A0\uFE0F Verify token legitimacy before using",
"\u{1F48E} Use story_approve_token to enable contract spending",
"\u{1F504} Use story_send_token to transfer to others"
]
};
} catch (error) {
throw new Error(`Failed to get token info: ${error.message}`);
} finally {
await agent.disconnect();
}
}
};
// src/mcp/wallet/get_transaction_history_tool.ts
import { z as z7 } from "zod";
import { formatEther as formatEther6 } from "viem";
var GetTransactionHistoryTool = {
name: "story_get_transaction_history",
description: "Get recent transaction history for the wallet or specified address",
schema: {
account_address: z7.string().regex(/^0x[0-9a-fA-F]{40}$/).optional().describe("Address to check (optional, defaults to wallet address)"),
limit: z7.number().min(1).max(100).default(20).describe("Number of transactions to retrieve (max 100)")
},
handler: async (agent, input) => {
try {
await agent.connect();
const targetAddress = input.account_address || agent.account.address;
const limit = input.limit || 20;
const currentBlock = await agent.publicClient.getBlockNumber();
const fromBlock = currentBlock - BigInt(1e4);
const recentTransactions = [];
const blocksToCheck = Math.min(Number(limit * 5), 1e3);
for (let i = 0; i < blocksToCheck && recentTransactions.length < limit; i++) {
try {
const blockNumber = currentBlock - BigInt(i);
const block = await agent.publicClient.getBlock({
blockNumber,
includeTransactions: true
});
for (const tx of block.transactions) {
if (typeof tx === "object") {
if ((tx.from?.toLowerCase() === targetAddress.toLowerCase() || tx.to?.toLowerCase() === targetAddress.toLowerCase()) && recentTransactions.length < limit) {
try {
const receipt = await agent.publicClient.getTransactionReceipt({
hash: tx.hash
});
recentTransactions.push({
hash: tx.hash,
block_number: block.number?.toString(),
timestamp: new Date(Number(block.timestamp) * 1e3).toISOString(),
from: tx.from,
to: tx.to,
value: tx.value ? formatEther6(tx.value) : "0",
gas_used: receipt.gasUsed.toString(),
gas_price: tx.gasPrice?.toString(),
status: receipt.status === "success" ? "success" : "failed",
type: tx.from?.toLowerCase() === targetAddress.toLowerCase() ? "sent" : "received",
is_contract_interaction: tx.to && tx.input !== "0x"
});
} catch (receiptError) {
recentTransactions.push({
hash: tx.hash,
block_number: block.number?.toString(),
timestamp: new Date(Number(block.timestamp) * 1e3).toISOString(),
from: tx.from,
to: tx.to,
value: tx.value ? formatEther6(tx.value) : "0",
gas_used: "N/A",
gas_price: tx.gasPrice?.toString(),
status: "unknown",
type: tx.from?.toLowerCase() === targetAddress.toLowerCase() ? "sent" : "received",
is_contract_interaction: tx.to && tx.input !== "0x"
});
}
}
}
}
} catch (blockError) {
console.error(`Error fetching block ${currentBlock - BigInt(i)}:`, blockError);
continue;
}
}
recentTransactions.sort((a, b) => {
const blockA = parseInt(a.block_number || "0");
const blockB = parseInt(b.block_number || "0");
return blockB - blockA;
});
const sentTransactions = recentTransactions.filter((tx) => tx.type === "sent");
const receivedTransactions = recentTransactions.filter((tx) => tx.type === "received");
const contractInteractions = recentTransactions.filter((tx) => tx.is_contract_interaction);
const totalSent = sentTransactions.reduce((sum, tx) => sum + parseFloat(tx.value), 0);
const totalReceived = receivedTransactions.reduce((sum, tx) => sum + parseFloat(tx.value), 0);
return {
status: "success",
message: `\u2705 Retrieved ${recentTransactions.length} recent transactions for ${targetAddress}`,
account_info: {
address: targetAddress,
network: agent.network,
is_own_wallet: targetAddress.toLowerCase() === agent.account.address.toLowerCase(),
blocks_searched: blocksToCheck,
from_block: fromBlock.toString(),
to_block: currentBlock.toString()
},
transaction_summary: {
total_transactions: recentTransactions.length,
sent_transactions: sentTransactions.length,
received_transactions: receivedTransactions.length,
contract_interactions: contractInteractions.length,
total_eth_sent: `${totalSent.toFixed(6)} ETH`,
total_eth_received: `${totalReceived.toFixed(6)} ETH`,
net_eth_flow: `${(totalReceived - totalSent).toFixed(6)} ETH`
},
transactions: recentTransactions.map((tx) => ({
...tx,
explorer_url: `${agent.networkInfo.blockExplorer}/tx/${tx.hash}`,
age: tx.timestamp ? getTimeAgo(new Date(tx.timestamp)) : "Unknown"
})),
network_info: {
network: agent.network,
block_explorer: agent.networkInfo.blockExplorer,
current_block: currentBlock.toString()
},
story_protocol_activity: {
ip_registrations: contractInteractions.filter(
(tx) => tx.to?.toLowerCase().includes("story") || tx.to?.toLowerCase().includes("ip")
).length,
licensing_transactions: contractInteractions.filter(
(tx) => tx.to?.toLowerCase().includes("license")
).length,
total_protocol_interactions: contractInteractions.length
},
next_steps: recentTransactions.length === 0 ? [
"\u{1F50D} No recent transactions found",
"\u{1F4A1} Start by funding your wallet with ETH",
"\u{1F3A8} Begin registering IP assets on Story Protocol"
] : [
"\u2705 Transaction history retrieved successfully",
"\u{1F50D} Click explorer URLs to view detailed transaction info",
`\u{1F4CA} Found ${contractInteractions.length} smart contract interactions`,
"\u{1F48E} Ready to analyze Story Protocol activity"
]
};
} catch (error) {
throw new Error(`Failed to get transaction history: ${error.message}`);
} finally {
await agent.disconnect();
}
}
};
var getTimeAgo = (date) => {
const now = /* @__PURE__ */ new Date();
const diffInSeconds = Math.floor((now.getTime() - date.getTime()) / 1e3);
if (diffInSeconds < 60) return `${diffInSeconds} seconds ago`;
if (diffInSeconds < 3600) return `${Math.floor(diffInSeconds / 60)} minutes ago`;
if (diffInSeconds < 86400) return `${Math.floor(diffInSeconds / 3600)} hours ago`;
return `${Math.floor(diffInSeconds / 86400)} days ago`;
};
// src/mcp/wallet/validate_address_tool.ts
import { z as z8 } from "zod";
import { isAddress } from "viem";
var ValidateAddressTool = {
name: "story_validate_address",
description: "Validate Ethereum address format and check if account exists on Story Protocol network",
schema: {
address: z8.string().describe("Ethereum address to validate")
},
handler: async (agent, input) => {
try {
await agent.connect();
const address = input.address;
const isValidFormat = isAddress(address);
if (!isValidFormat) {
return {
status: "invalid",
message: `\u274C Invalid Ethereum address format: ${address}`,
validation_details: {
address,
is_valid_format: false,
is_checksum_valid: false,
exists_on_network: false,
error: "Invalid address format - must be 42 characters starting with 0x"
},
recommendations: [
"\u{1F50D} Check that address starts with '0x'",
"\u{1F4CF} Ensure address is exactly 42 characters long",
"\u{1F524} Verify hexadecimal characters (0-9, a-f, A-F)",
"\u{1F4CB} Copy address directly from source to avoid typos"
]
};
}
const validAddress = address;
const checksumAddress = address;
const isChecksumValid = isAddress(address);
return {
status: "valid",
message: `\u2705 Valid Ethereum address: ${validAddress}`,
validation_details: {
address: validAddress,
is_valid_format: isValidFormat,
is_checksum_valid: isChecksumValid,
network: agent.network
},
network_info: {
network: agent.network,
chain_id: await agent.publicClient.getChainId(),
block_explorer: agent.networkInfo.blockExplorer,
explorer_url: `${agent.networkInfo.blockExplorer}/address/${validAddress}`
}
};
} catch (error) {
throw new Error(`Failed to validate address: ${error.message}`);
} finally {
await agent.disconnect();
}
}
};
// src/mcp/wallet/wrap_ip_tool.ts
import { z as z9 } from "zod";
import { parseEther as parseEther4, formatEther as formatEther7 } from "viem";
import { WIP_TOKEN_ADDRESS as WIP_TOKEN_ADDRESS6 } from "@story-protocol/core-sdk";
var WrapIPTool = {
name: "story_wrap_ip",
description: "Wrap IP tokens to WIP tokens for use in licensing and trading",
schema: {
amount: z9.number().positive().describe("Amount of IP tokens to wrap into WIP tokens"),
check_balance: z9.boolean().default(true).describe("Check IP balance before wrapping")
},
handler: async (agent, input) => {
try {
await agent.connect();
const amount = input.amount;
const amountWei = parseEther4(amount.toString());
console.error(`\u{1F504} Wrapping ${amount} IP tokens to WIP...`);
if (input.check_balance) {
console.error(`\u{1F4B0} Checking IP token balance...`);
try {
const ipBalance = await agent.publicClient.getBalance({
address: agent.account.address
});
const ipBalanceFormatted = Number(formatEther7(ipBalance));
if (ipBalanceFormatted < amount) {
throw new Error(`Insufficient IP balance. Required: ${amount} IP, Available: ${ipBalanceFormatted} IP`);
}
console.error(`\u2705 Sufficient IP balance: ${ipBalanceFormatted} IP`);
} catch (error) {
console.error(`\u26A0\uFE0F Could not verify IP balance: ${error}`);
}
}
console.error(`\u{1F504} Executing wrap transaction...`);
const response = await agent.client.wipClient.deposit({
amount: amountWei
});
console.error(`\u{1F4CA} Fetching updated balances...`);
let newWIPBalance = "0";
try {
const wipBalance = await agent.publicClient.readContract({
address: WIP_TOKEN_ADDRESS6,
// WIP token address
abi: [
{
name: "balanceOf",
type: "function",
stateMutability: "view",
inputs: [{ name: "account", type: "address" }],
outputs: [{ name: "", type: "uint256" }]
}
],
functionName: "balanceOf",
args: [agent.account.address]
});
newWIPBalance = formatEther7(wipBalance);
} catch (error) {
console.error(`\u26A0\uFE0F Could not fetch updated balances: ${error}`);
}
console.error(`\u2705 Successfully wrapped ${amount} IP to WIP!`);
return {
status: "success",
message: `\u2705 Successfully wrapped ${amount} IP tokens to WIP`,
wrap_details: {
amount_wrapped: `${amount} IP`,
received: `${amount} WIP`,
exchange_rate: "1:1 (IP to WIP)",
wrapped_at: (/* @__PURE__ */ new Date()).toISOString()
},
transaction_info: {
tx_hash: response.txHash,
block_explorer: `${agent.networkInfo.blockExplorer}/tx/${response.txHash}`,
gas_used: "Varies by network congestion"
},
balance_changes: {
wip_balance: {
before: `${Number(newWIPBalance) - amount} WIP (estimated)`,
after: `${newWIPBalance} WIP`,
change: `+${amount} WIP`
}
},
token_info: {
wip_token: {
name: "Wrapped IP Token",
symbol: "WIP",
address: WIP_TOKEN_ADDRESS6,
type: "ERC20 wrapper for IP token"
}
},
use_cases: {
wip_advantages: [
"\u{1F3AB} Required for license token minting fees",
"\u{1F4B0} Used for royalty payments",
"\u{1F504} ERC20 compatibility for DeFi integrations",
"\u{1F3A8} Derivative work licensing payments",
"\u{1F4B1} Trading on DEXs and markets"
],
when_to_wrap: [
"Before minting license tokens with fees",
"To pay for derivative licensing",
"For revenue sharing payments",
"To interact with Story Protocol contracts",
"For trading on secondary markets"
]
},
next_steps: [
"\u2705 WIP tokens ready for Story Protocol operations",
"\u{1F3AB} Use WIP for license token minting fees",
"\u{1F4B0} Pay royalties and licensing fees",
"\u{1F504} Unwrap back to IP using story_unwrap_wip if needed",
`\u{1F48E} Current WIP balance: ${newWIPBalance} WIP`
]
};
} catch (error) {
console.error("\u274C Failed to wrap IP tokens:", error);
throw new Error(`Failed to wrap IP tokens: ${error.message}`);
} finally {
await agent.disconnect();
}
}
};
// src/mcp/wallet/unwrap_wip_tool.ts
import { z as z10 } from "zod";
import { parseEther as parseEther5, formatEther as formatEther8 } from "viem";
import { WIP_TOKEN_ADDRESS as WIP_TOKEN_ADDRESS7 } from "@story-protocol/core-sdk";
var UnwrapWIPTool = {
name: "story_unwrap_wip",
description: "Unwrap WIP toke