Skip to main content
Glama

export_agent

Export agent configurations to JSON files for backup, sharing, or migration. Save locally or upload to XBackbone storage.

Instructions

Export an agent's configuration to a JSON file and optionally upload it. Use import_agent to recreate the agent later, or clone_agent for a quick copy. Use list_agents to find agent IDs.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
agent_idYesThe ID of the agent to export.
output_pathNoOptional: Path to save the exported JSON file (e.g., my_agent.json). Defaults to agent_{agent_id}.json.
return_base64NoOptional: If true, return the JSON content as base64 string in the response. Defaults to false.
upload_to_xbackboneNoOptional: If true, upload the exported file to XBackbone. Defaults to false.
xbackbone_urlNoOptional: URL of the XBackbone instance. Uses XBACKBONE_URL environment variable if not provided.
xbackbone_tokenNoOptional: Token for XBackbone authentication. Uses XBACKBONE_TOKEN environment variable if not provided.

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
successYes
file_pathNo
agent_dataNo
upload_urlNo
base64_contentNo

Implementation Reference

  • Main handler function that fetches agent configuration, saves it as JSON file, optionally uploads to XBackbone, and returns the file path and optional URL or base64 data.
    export async function handleExportAgent(server, args) {
        if (!args?.agent_id) {
            server.createErrorResponse('Missing required argument: agent_id');
        }
    
        const agentId = args.agent_id;
        const outputPath = args.output_path || `agent_${agentId}.json`;
        const returnBase64 = args.return_base64 ?? false;
        const uploadToXBackbone = args.upload_to_xbackbone ?? false; // Default to false for security
        const xbackboneUrl = args.xbackbone_url || process.env.XBACKBONE_URL; // No hardcoded default
        const xbackboneToken = args.xbackbone_token || process.env.XBACKBONE_TOKEN; // No hardcoded default
    
        try {
            const headers = server.getApiHeaders();
            const encodedAgentId = encodeURIComponent(agentId);
    
            // Step 1: Fetch agent export data
            const response = await server.api.get(`/agents/${encodedAgentId}/export`, { headers });
            const agentData = response.data; // Assuming response.data is the AgentSchema JSON
    
            if (!agentData) {
                throw new Error('Received empty data from agent export endpoint.');
            }
    
            const agentJsonString = JSON.stringify(agentData, null, 2);
    
            // Step 2: Save locally
            const absoluteOutputPath = path.resolve(outputPath);
            try {
                fs.writeFileSync(absoluteOutputPath, agentJsonString);
            } catch (writeError) {
                logger.error(`Error writing agent export to ${absoluteOutputPath}:`, writeError);
                server.createErrorResponse(
                    `Failed to save agent export to ${absoluteOutputPath}: ${writeError.message}`,
                );
            }
    
            // Step 3: Upload to XBackbone if requested
            let xbackboneResult = null;
            if (uploadToXBackbone) {
                if (!xbackboneUrl || !xbackboneToken) {
                    logger.warn('XBackbone URL or Token not configured, skipping upload.');
                } else {
                    try {
                        const form = new FormData();
                        form.append(
                            'upload',
                            fs.createReadStream(absoluteOutputPath),
                            path.basename(absoluteOutputPath),
                        );
                        form.append('token', xbackboneToken);
    
                        const uploadResponse = await axios.post(`${xbackboneUrl}/upload`, form, {
                            headers: {
                                ...form.getHeaders(),
                                // Add any other necessary headers for XBackbone if needed
                            },
                            // If XBackbone uses self-signed certs, might need:
                            // httpsAgent: new https.Agent({ rejectUnauthorized: false })
                        });
    
                        if (
                            uploadResponse.status >= 200 &&
                            uploadResponse.status < 300 &&
                            uploadResponse.data?.url
                        ) {
                            xbackboneResult = {
                                url: uploadResponse.data.url,
                                raw_url: `${uploadResponse.data.url}/raw`,
                                // Assuming XBackbone provides a delete URL structure like this
                                delete_url: `${uploadResponse.data.url}/delete/${xbackboneToken}`,
                            };
                            logger.info(
                                `Successfully uploaded ${absoluteOutputPath} to XBackbone: ${xbackboneResult.url}`,
                            );
                        } else {
                            logger.error(
                                `XBackbone upload failed with status ${uploadResponse.status}:`,
                                uploadResponse.data,
                            );
                            // Don't fail the whole tool, just report the upload issue
                            xbackboneResult = {
                                error: `Upload failed with status ${uploadResponse.status}`,
                            };
                        }
                    } catch (uploadError) {
                        logger.error('Error uploading to XBackbone:', uploadError);
                        xbackboneResult = { error: `Upload failed: ${uploadError.message}` };
                    }
                }
            }
    
            // Step 4: Prepare and return result
            const resultPayload = {
                agent_id: agentId,
                file_path: absoluteOutputPath,
            };
    
            if (xbackboneResult && !xbackboneResult.error) {
                resultPayload.xbackbone_url = xbackboneResult.url;
            }
    
            if (returnBase64) {
                resultPayload.base64_data = Buffer.from(agentJsonString).toString('base64');
            }
    
            return {
                content: [
                    {
                        type: 'text',
                        text: JSON.stringify(resultPayload),
                    },
                ],
            };
        } catch (error) {
            // Handle potential 404 if agent not found, or other API errors
            if (error.response && error.response.status === 404) {
                server.createErrorResponse(`Agent not found: ${agentId}`);
            }
            logger.error('Error:', error.response?.data || error.message);
            server.createErrorResponse(`Failed to export agent ${agentId}: ${error.message}`);
        }
    }
  • Tool definition including name, description, and input schema for parameters like agent_id, output_path, return_base64, upload_to_xbackbone, etc.
    export const exportAgentDefinition = {
        name: 'export_agent',
        description:
            "Export an agent's configuration to a JSON file and optionally upload it. Use import_agent to recreate the agent later, or clone_agent for a quick copy. Use list_agents to find agent IDs.",
        inputSchema: {
            type: 'object',
            properties: {
                agent_id: {
                    type: 'string',
                    description: 'The ID of the agent to export.',
                },
                output_path: {
                    type: 'string',
                    description:
                        'Optional: Path to save the exported JSON file (e.g., my_agent.json). Defaults to agent_{agent_id}.json.',
                },
                return_base64: {
                    type: 'boolean',
                    description:
                        'Optional: If true, return the JSON content as base64 string in the response. Defaults to false.',
                    default: false,
                },
                upload_to_xbackbone: {
                    type: 'boolean',
                    description:
                        'Optional: If true, upload the exported file to XBackbone. Defaults to false.',
                    default: false,
                },
                xbackbone_url: {
                    type: 'string',
                    description:
                        'Optional: URL of the XBackbone instance. Uses XBACKBONE_URL environment variable if not provided.',
                },
                xbackbone_token: {
                    type: 'string',
                    description:
                        'Optional: Token for XBackbone authentication. Uses XBACKBONE_TOKEN environment variable if not provided.',
                },
            },
            required: ['agent_id'],
        },
    };
  • Registers the export_agent tool by including its definition in the list of tools for listTools and mapping the tool name to its handler in the switch statement for callTool.
    export function registerToolHandlers(server) {
        // Collect all tool definitions
        const allTools = [
            listAgentsToolDefinition,
            promptAgentToolDefinition,
            listAgentToolsDefinition,
            createAgentToolDefinition,
            attachToolToolDefinition,
            listMemoryBlocksToolDefinition,
            readMemoryBlockToolDefinition,
            updateMemoryBlockToolDefinition,
            attachMemoryBlockToolDefinition,
            createMemoryBlockToolDefinition,
            deleteMemoryBlockToolDefinition,
            searchMemoryDefinition,
            uploadToolToolDefinition,
            listMcpToolsByServerDefinition,
            listMcpServersDefinition,
            retrieveAgentDefinition,
            modifyAgentDefinition,
            deleteAgentDefinition,
            listLlmModelsDefinition,
            listEmbeddingModelsDefinition,
            listPassagesDefinition,
            createPassageDefinition,
            modifyPassageDefinition,
            deletePassageDefinition,
            searchArchivalMemoryDefinition,
            exportAgentDefinition,
            importAgentDefinition,
            cloneAgentDefinition,
            bulkAttachToolDefinition,
            getAgentSummaryDefinition,
            bulkDeleteAgentsDefinition,
            addMcpToolToLettaDefinition,
            listPromptsToolDefinition,
            usePromptToolDefinition,
            listMessagesDefinition,
            createConversationEntryDefinition,
        ];
    
        // Enhance all tools with output schemas and improved descriptions
        const enhancedTools = enhanceAllTools(allTools);
    
        // Register tool definitions
        server.server.setRequestHandler(ListToolsRequestSchema, async () => ({
            tools: enhancedTools,
        }));
    
        // Register tool call handler
        server.server.setRequestHandler(CallToolRequestSchema, async (request) => {
            switch (request.params.name) {
                case 'list_agents':
                    return handleListAgents(server, request.params.arguments);
                case 'prompt_agent':
                    return handlePromptAgent(server, request.params.arguments);
                case 'list_agent_tools':
                    return handleListAgentTools(server, request.params.arguments);
                case 'create_agent':
                    return handleCreateAgent(server, request.params.arguments);
                case 'attach_tool':
                    return handleAttachTool(server, request.params.arguments);
                case 'list_memory_blocks':
                    return handleListMemoryBlocks(server, request.params.arguments);
                case 'read_memory_block':
                    return handleReadMemoryBlock(server, request.params.arguments);
                case 'update_memory_block':
                    return handleUpdateMemoryBlock(server, request.params.arguments);
                case 'attach_memory_block':
                    return handleAttachMemoryBlock(server, request.params.arguments);
                case 'create_memory_block':
                    return handleCreateMemoryBlock(server, request.params.arguments);
                case 'delete_memory_block':
                    return handleDeleteMemoryBlock(server, request.params.arguments);
                case 'search_memory':
                    return handleSearchMemory(server, request.params.arguments);
                case 'upload_tool':
                    return handleUploadTool(server, request.params.arguments);
                case 'list_mcp_tools_by_server':
                    return handleListMcpToolsByServer(server, request.params.arguments);
                case 'list_mcp_servers':
                    return handleListMcpServers(server, request.params.arguments);
                case 'retrieve_agent':
                    return handleRetrieveAgent(server, request.params.arguments);
                case 'modify_agent':
                    return handleModifyAgent(server, request.params.arguments);
                case 'delete_agent':
                    return handleDeleteAgent(server, request.params.arguments);
                case 'list_llm_models':
                    return handleListLlmModels(server, request.params.arguments);
                case 'list_embedding_models':
                    return handleListEmbeddingModels(server, request.params.arguments);
                case 'list_passages':
                    return handleListPassages(server, request.params.arguments);
                case 'create_passage':
                    return handleCreatePassage(server, request.params.arguments);
                case 'modify_passage':
                    return handleModifyPassage(server, request.params.arguments);
                case 'delete_passage':
                    return handleDeletePassage(server, request.params.arguments);
                case 'search_archival_memory':
                    return handleSearchArchivalMemory(server, request.params.arguments);
                case 'export_agent':
                    return handleExportAgent(server, request.params.arguments);
                case 'import_agent':
                    return handleImportAgent(server, request.params.arguments);
                case 'clone_agent':
                    return handleCloneAgent(server, request.params.arguments);
                case 'bulk_attach_tool_to_agents':
                    return handleBulkAttachToolToAgents(server, request.params.arguments);
                case 'get_agent_summary':
                    return handleGetAgentSummary(server, request.params.arguments);
                case 'bulk_delete_agents':
                    return handleBulkDeleteAgents(server, request.params.arguments);
                case 'add_mcp_tool_to_letta':
                    return handleAddMcpToolToLetta(server, request.params.arguments);
                case 'list_prompts':
                    return handleListPrompts(server, request.params.arguments);
                case 'use_prompt':
                    return handleUsePrompt(server, request.params.arguments);
                case 'list_messages':
                    return handleListMessages(server, request.params.arguments);
                case 'create_conversation_entry':
                    return handleCreateConversationEntry(server, request.params.arguments);
                default:
                    throw new McpError(
                        ErrorCode.MethodNotFound,
                        `Unknown tool: ${request.params.name}`,
                    );
            }
        });
    }
  • src/tools/index.js:9-9 (registration)
    Import statement bringing in the handler and definition from the export-agent module.
    import { handleExportAgent, exportAgentDefinition } from './agents/export-agent.js';
Behavior4/5

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

Annotations only provide a title, so the description carries the full burden. It clearly describes the core behavior (export to JSON file with optional upload) and mentions the optional upload functionality to XBackbone. However, it doesn't mention potential side effects, rate limits, or authentication requirements beyond the XBackbone parameters.

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

Conciseness5/5

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

The description is perfectly concise with three focused sentences: the core functionality, when to use alternatives, and a prerequisite. Every sentence earns its place with no wasted words, and the most important information (what the tool does) comes first.

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

Completeness5/5

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

Given the presence of a comprehensive input schema (100% coverage) and an output schema (implied by context signals), the description provides exactly what's needed: clear purpose, usage guidelines, and behavioral context. The description doesn't need to explain return values since an output schema exists.

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?

Schema description coverage is 100%, so the schema already fully documents all 6 parameters. The description adds no additional parameter semantics beyond what's in the schema descriptions. The baseline of 3 is appropriate when the schema does all the parameter documentation work.

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

Purpose5/5

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

The description clearly states the specific action ('Export an agent's configuration to a JSON file and optionally upload it') and distinguishes it from sibling tools by explicitly naming alternatives (import_agent, clone_agent, list_agents). It specifies both the resource (agent configuration) and output format (JSON file).

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

Usage Guidelines5/5

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

The description provides explicit guidance on when to use this tool versus alternatives: 'Use import_agent to recreate the agent later, or clone_agent for a quick copy. Use list_agents to find agent IDs.' This gives clear context for tool selection and prerequisites.

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/oculairmedia/Letta-MCP-server'

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