Skip to content

AI Agents & MCPs & AI Workflow Automation • (~400 MCP servers for AI agents) • AI Automation / AI Agent with MCPs • AI Workflows & AI Agents • MCPs for AI Agents

4.0 KB
Raw Blame
import { Permission } from '@activepieces/core-utils'
import { McpToolDefinition, ProjectScopedMcpServer } from '@activepieces/shared'
import { FastifyBaseLogger } from 'fastify'
import { fieldService } from '../../tables/field/field.service'
import { tableService } from '../../tables/table/table.service'
import { mcpUtils } from './mcp-utils'
import { formatFieldInfo } from './table-utils'

export const apListTablesTool = (mcp: ProjectScopedMcpServer, log: FastifyBaseLogger): McpToolDefinition => {
    return {
        title: 'ap_list_tables',
        permission: Permission.READ_TABLE,
        description: 'List all tables in the current project with their fields (name, type, id) and row counts. Use this to discover available tables before querying or modifying data. Each table has two ids: use "id" with the record/field MCP tools (ap_insert_records, ap_find_records, ap_manage_fields, etc.), and use "externalId" as the table_id value when configuring a Tables piece step inside a flow.',
        inputSchema: {},
        annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },
        execute: async () => {
            try {
                const result = await tableService.list({
                    projectId: mcp.projectId,
                    cursor: undefined,
                    limit: 100,
                    name: undefined,
                    externalIds: undefined,
                    folderId: undefined,
                    includeRowCount: true,
                })

                if (result.data.length === 0) {
                    return {
                        content: [{ type: 'text', text: 'No tables found in this project.' }],
                        structuredContent: { tables: [], count: 0 },
                    }
                }

                const tableIds = result.data.map(t => t.id)
                const fieldsByTable = await fieldService.getAllByTableIds({
                    projectId: mcp.projectId,
                    tableIds,
                })

                const tableDetails = result.data.map((table) => {
                    const fields = fieldsByTable.get(table.id) ?? []
                    const rowCount = table.rowCount ?? 0
                    const fieldLines = fields.map(f => `    - ${formatFieldInfo(f)}`).join('\n')
                    return `- ${table.name} (id: ${table.id}, externalId: ${table.externalId}) — ${rowCount} records\n  Fields:\n${fieldLines}`
                })

                const structured = {
                    tables: result.data.map((table) => {
                        const fields = fieldsByTable.get(table.id) ?? []
                        return {
                            id: table.id,
                            externalId: table.externalId,
                            name: table.name,
                            rowCount: table.rowCount ?? 0,
                            fields: fields.map(f => ({ id: f.id, externalId: f.externalId, name: f.name, type: f.type })),
                        }
                    }),
                    count: result.data.length,
                }

                const idHint = '\n\nℹ️ Use "id" with the record/field tools; use "externalId" as table_id when configuring a Tables piece step in a flow.'
                const output = tableDetails.join('\n\n') + idHint
                const truncationNote = result.data.length >= 100
                    ? '\n\n⚠️ Showing first 100 tables. There may be more in this project.'
                    : ''
                return {
                    content: [{
                        type: 'text',
                        text: output + truncationNote,
                    }],
                    structuredContent: structured,
                }
            }
            catch (err) {
                log.error({ error: err, project: { id: mcp.projectId } }, 'ap_list_tables failed')
                return mcpUtils.mcpToolError('Failed to list tables', err)
            }
        },
    }
}