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
| Name | Required | Description | Default |
|---|---|---|---|
| agent_id | Yes | The ID of the agent to export. | |
| output_path | No | Optional: Path to save the exported JSON file (e.g., my_agent.json). Defaults to agent_{agent_id}.json. | |
| return_base64 | No | Optional: If true, return the JSON content as base64 string in the response. Defaults to false. | |
| upload_to_xbackbone | No | Optional: If true, upload the exported file to XBackbone. Defaults to false. | |
| xbackbone_url | No | Optional: URL of the XBackbone instance. Uses XBACKBONE_URL environment variable if not provided. | |
| xbackbone_token | No | Optional: Token for XBackbone authentication. Uses XBACKBONE_TOKEN environment variable if not provided. |
Implementation Reference
- src/tools/agents/export-agent.js:13-135 (handler)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'], }, };
- src/tools/index.js:101-232 (registration)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';