add
Add data to a specified collection in UniCloudDB-MCP using a standardized interface for efficient database CRUD operations.
Input Schema
TableJSON Schema
| Name | Required | Description | Default |
|---|---|---|---|
| collection | Yes | 集合名称 | |
| data | Yes | 要添加的数据 (object/array) |
Implementation Reference
- database.js:262-276 (handler)The handler function for the 'add' tool that destructures parameters, calls the addToDatabase helper to insert data, and returns formatted success or error response.async function handleAddTool(params, dbUrl) { const { collection, data } = params; try { const result = await addToDatabase(collection, data, dbUrl); return { content: [{ type: 'text', text: JSON.stringify(result, null, 2) }], }; } catch (error) { return { content: [{ type: 'text', text: error.message }], isError: true, }; } }
- database.js:393-400 (schema)The tool definition for 'add' including its name, Zod input schema (collection string, data record), and handler reference.addTool: { name: 'add', params: { collection: z.string().describe('集合名称'), data: z.record(z.any()).describe('要添加的数据 (object/array)'), }, handler: (params) => handleAddTool(params, dbServiceUrl), },
- index.js:44-44 (registration)Registration of the 'add' tool on the MCP server using the name, params schema, and handler from the tools object.server.tool(tools.addTool.name, tools.addTool.params, tools.addTool.handler);
- database.js:89-125 (helper)Core helper function that performs the HTTP POST request to the uniCloud database service to insert data into the collection, with timeout and error handling.async function addToDatabase(collection, data, dbUrl = DEFAULT_DB_URL) { try { const controller = new AbortController(); const timeoutId = setTimeout(() => controller.abort(), REQUEST_TIMEOUT); // 使用传入的dbUrl或默认URL const targetUrl = dbUrl || DEFAULT_DB_URL; // console.log('添加操作使用URL:', targetUrl); const response = await fetch(targetUrl, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ operation: { collection, action: 'insert', data, }, }), signal: controller.signal, }); clearTimeout(timeoutId); const result = await response.json(); if (result.code !== 0) { throw new Error(result.msg || '添加失败'); } return result.data; } catch (error) { if (error.name === 'AbortError') { throw new Error(`添加超时: 请求超过${REQUEST_TIMEOUT}毫秒`); } throw new Error(`添加错误: ${error.message}`); } }