Skip to main content
Glama

generate_aptos_component

Create new Aptos blockchain components like tables or modules for your project. Specify component type, name, and project directory to generate required files.

Instructions

Generate a new component for an Aptos project. Args: component_type: Type of component (table, module, etc.) component_name: Name of the component project_dir: Project directory path options: Additional options as a string

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
component_typeYes
component_nameYes
project_dirYes
optionsNo

Implementation Reference

  • MCP decorator that registers the generate_aptos_component tool with the FastMCP server.
    @mcp.tool()
  • The primary handler function implementing the tool logic. It supports generating move modules, react components, client functions, and tables by calling helper functions and writing generated code to the appropriate paths in the project directory.
    async def generate_aptos_component(component_type: str, component_name: str, project_dir: str, options: str = "") -> str: """ Generate a new component for an Aptos project. Args: component_type: Type of component (table, module, etc.) component_name: Name of the component project_dir: Project directory path options: Additional options as a string """ supported_types = ["move-module", "react-component", "client-function", "table"] if component_type not in supported_types: return f"Unsupported component type. Choose from: {', '.join(supported_types)}" project_dir = os.path.expanduser(project_dir) # Expand ~ in paths if not os.path.exists(project_dir): return f"Project directory not found: {project_dir}" try: # Different command logic based on component type if component_type == "move-module": module_code = generate_move_module(component_name) module_path = os.path.join(project_dir, "move", "sources", f"{component_name}.move") os.makedirs(os.path.dirname(module_path), exist_ok=True) with open(module_path, "w") as f: f.write(module_code) return f"Generated Move module at {module_path}" elif component_type == "react-component": component_code = generate_react_component(component_name, options) component_path = os.path.join(project_dir, "client", "src", "components", f"{component_name}.tsx") os.makedirs(os.path.dirname(component_path), exist_ok=True) with open(component_path, "w") as f: f.write(component_code) return f"Generated React component at {component_path}" elif component_type == "client-function": function_code = generate_client_function(component_name, options) function_path = os.path.join(project_dir, "client", "src", "utils", f"{component_name}.ts") os.makedirs(os.path.dirname(function_path), exist_ok=True) with open(function_path, "w") as f: f.write(function_code) return f"Generated client function at {function_path}" elif component_type == "table": table_code = generate_move_table(component_name, options) table_path = os.path.join(project_dir, "move", "sources", f"{component_name}_table.move") os.makedirs(os.path.dirname(table_path), exist_ok=True) with open(table_path, "w") as f: f.write(table_code) return f"Generated Move table at {table_path}" return f"Unknown component type: {component_type}" except Exception as e: return f"Error generating component: {str(e)}"
  • Helper function that generates TypeScript React component code, optionally with wallet integration for Aptos dApps.
    def generate_react_component(name: str, options: str) -> str: """Generate a React component for Aptos dApp frontend""" use_wallet = "wallet" in options.lower() wallet_imports = """ import { useWallet } from "@aptos-labs/wallet-adapter-react"; import { AptosClient } from "aptos"; """ if use_wallet else "" wallet_hooks = """ const { account, signAndSubmitTransaction } = useWallet(); const isConnected = !!account; """ if use_wallet else "" return f""" import React, {{ useState }} from "react";{wallet_imports} export const {name} = () => {{{wallet_hooks} const [loading, setLoading] = useState(false); // Add your component logic here const handleAction = async () => {{ setLoading(true); try {{ // Your action logic here {''' // Example transaction if using wallet if (account) { const payload = { type: "entry_function_payload", function: "your_module::your_function", type_arguments: [], arguments: [] }; const response = await signAndSubmitTransaction(payload); console.log("Transaction submitted:", response); } ''' if use_wallet else '// Implement your action here'} }} catch (error) {{ console.error("Error:", error); }} finally {{ setLoading(false); }} }}; return ( <div className="p-4 border rounded-lg shadow-sm bg-white"> <h2 className="text-xl font-bold mb-4">{name}</h2> {''' {!isConnected ? ( <p className="text-gray-500">Please connect your wallet</p> ) : ( <button onClick={handleAction} disabled={loading} className="px-4 py-2 bg-blue-500 text-white rounded-lg disabled:opacity-50" > {loading ? "Processing..." : "Perform Action"} </button> )} ''' if use_wallet else ''' <button onClick={handleAction} disabled={loading} className="px-4 py-2 bg-blue-500 text-white rounded-lg disabled:opacity-50" > {loading ? "Processing..." : "Perform Action"} </button> '''} </div> ); }}; export default {name}; """
  • Helper function that generates a TypeScript client utility function for Aptos blockchain interactions.
    def generate_client_function(name: str, options: str) -> str: """Generate a client utility function for interacting with Aptos blockchain""" return f""" import {{ AptosClient, Types, HexString }} from "aptos"; // Aptos network configuration const NODE_URL = process.env.NEXT_PUBLIC_APTOS_NODE_URL || "https://fullnode.devnet.aptoslabs.com"; const client = new AptosClient(NODE_URL); /** * {name} - Utility function for interacting with Aptos blockchain * @param args - Function arguments * @returns Result of the operation */ export async function {name.lower()}(args: any) {{ try {{ // Implementation goes here // Example: Query resources, submit transactions, etc. // Example resource query: // const resource = await client.getAccountResource( // new HexString(accountAddress), // "0x1::coin::CoinStore<0x1::aptos_coin::AptosCoin>" // ); return {{ success: true, data: null // Replace with actual data }}; }} catch (error) {{ console.error(`Error in {name}:`, error); return {{ success: false, error: error instanceof Error ? error.message : String(error) }}; }} }} // Add more helper functions below """
  • Helper function that generates a complete Move module implementing a table with key-value storage and CRUD operations.
    def generate_move_table(name: str, options: str) -> str: """Generate a Move table implementation""" return f""" module {name}::table {{ use std::signer; use aptos_framework::account; use aptos_framework::table::{{\n Table,\n new,\n add,\n borrow,\n borrow_mut,\n contains,\n remove\n }}; // Error codes const E_NOT_INITIALIZED: u64 = 1; const E_ALREADY_INITIALIZED: u64 = 2; const E_KEY_NOT_FOUND: u64 = 3; const E_KEY_ALREADY_EXISTS: u64 = 4; struct {name.capitalize()}Store has key {{ items: Table<KeyType, ValueType>, }} /// Key type for the table struct KeyType has copy, drop, store {{ // Define your key structure id: u64, }} /// Value type for the table struct ValueType has copy, drop, store {{ // Define your value structure data: u64, name: vector<u8>, }} /// Initialize the table public entry fun initialize(account: &signer) {{ let addr = signer::address_of(account); assert!(!exists<{name.capitalize()}Store>(addr), E_ALREADY_INITIALIZED); move_to(account, {name.capitalize()}Store {{ items: new<KeyType, ValueType>(), }}); }} /// Add an item to the table public entry fun add_item( account: &signer, id: u64, data: u64, name: vector<u8> ) acquires {name.capitalize()}Store {{ let addr = signer::address_of(account); assert!(exists<{name.capitalize()}Store>(addr), E_NOT_INITIALIZED); let store = borrow_mut<{name.capitalize()}Store>(addr); let key = KeyType {{ id }}; assert!(!contains(&store.items, key), E_KEY_ALREADY_EXISTS); add(&mut store.items, key, ValueType {{ data, name }}); }} /// Get an item from the table (public view function) #[view] public fun get_item(addr: address, id: u64): (u64, vector<u8>) acquires {name.capitalize()}Store {{ assert!(exists<{name.capitalize()}Store>(addr), E_NOT_INITIALIZED); let store = borrow<{name.capitalize()}Store>(addr); let key = KeyType {{ id }}; assert!(contains(&store.items, key), E_KEY_NOT_FOUND); let value = borrow(&store.items, key); (value.data, value.name) }} /// Remove an item from the table public entry fun remove_item(account: &signer, id: u64) acquires {name.capitalize()}Store {{ let addr = signer::address_of(account); assert!(exists<{name.capitalize()}Store>(addr), E_NOT_INITIALIZED); let store = borrow_mut<{name.capitalize()}Store>(addr); let key = KeyType {{ id }}; assert!(contains(&store.items, key), E_KEY_NOT_FOUND); remove(&mut store.items, key); }} }} """

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/Tlazypanda/aptos-mcp-server'

If you have feedback or need assistance with the MCP directory API, please join our Discord server