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);
        }}
    }}
    """
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

No annotations are provided, so the description carries the full burden of behavioral disclosure. It states the tool generates a component but doesn't describe what that entails—whether it creates files, modifies existing ones, requires specific permissions, or has side effects like initializing dependencies. For a tool with potential file system impacts, this lack of detail is a significant gap.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness4/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is concise and well-structured: a clear purpose statement followed by a bullet-point list of parameters. Each sentence earns its place by defining the tool and its inputs. It could be slightly more front-loaded with key behavioral details, but overall it's efficient without unnecessary verbiage.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness2/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the complexity (generating components in a development environment), lack of annotations, no output schema, and 0% schema description coverage, the description is incomplete. It doesn't cover behavioral traits, output format, error handling, or dependencies on sibling tools. For a tool that likely interacts with file systems and project structures, more context is needed for safe and effective use.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

The description lists all four parameters with brief explanations, but schema description coverage is 0%, meaning the schema provides no additional details. The description adds basic semantics (e.g., 'Type of component (table, module, etc.)'), which compensates somewhat. However, it doesn't elaborate on allowed values for 'component_type' or format for 'options', leaving ambiguity. Baseline is adjusted upward from 1 due to parameter listing.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the tool's purpose: 'Generate a new component for an Aptos project.' It specifies the verb ('generate') and resource ('component for an Aptos project'), which is clear. However, it doesn't explicitly differentiate from sibling tools like 'create_aptos_project' or 'aptos_abi_generate', leaving some ambiguity about scope boundaries.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines2/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides no guidance on when to use this tool versus alternatives. It doesn't mention prerequisites (e.g., whether an Aptos project must exist), compare to siblings like 'create_aptos_project' (which might handle project setup), or specify scenarios where this tool is appropriate. Usage is implied but not explicitly defined.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

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