Skip to main content
Glama
gendosu

Notion MCP Server

by gendosu

API-post-database-query

Query a Notion database by ID, filter properties, apply sort criteria, and paginate results using the Notion API. Retrieve specific page data efficiently with customizable filters and sorting options.

Instructions

Notion | Query a database

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
archivedNo
database_idYesIdentifier for a Notion database.
filterNoWhen supplied, limits which pages are returned based on the [filter conditions](ref:post-database-query-filter).
filter_propertiesNoA list of page property value IDs associated with the database. Use this param to limit the response to a specific page property value or values for pages that meet the `filter` criteria.
in_trashNo
page_sizeNoThe number of items from the full list desired in the response. Maximum: 100
sortsNoWhen supplied, orders the results based on the provided [sort criteria](ref:post-database-query-sort).
start_cursorNoWhen supplied, returns a page of results starting after the cursor provided. If not supplied, this endpoint will return the first page of results.

Implementation Reference

  • MCP call tool request handler that executes all proxied OpenAPI operations, including 'API-post-database-query'. Resolves operation via name lookup and calls HTTP client.
    this.server.setRequestHandler(CallToolRequestSchema, async (request) => {
      const { name, arguments: params } = request.params
    
      // Find the operation in OpenAPI spec
      const operation = this.findOperation(name)
      if (!operation) {
        throw new Error(`Method ${name} not found`)
      }
    
      try {
        // Execute the operation
        const response = await this.httpClient.executeOperation(operation, params)
    
        // Convert response to MCP format
        return {
          content: [
            {
              type: 'text', // currently this is the only type that seems to be used by mcp server
              text: JSON.stringify(response.data), // TODO: pass through the http status code text?
            },
          ],
        }
      } catch (error) {
        console.error('Error in tool call', error)
        if (error instanceof HttpClientError) {
          console.error('HttpClientError encountered, returning structured error', error)
          const data = error.data?.response?.data ?? error.data ?? {}
          return {
            content: [
              {
                type: 'text',
                text: JSON.stringify({
                  status: 'error', // TODO: get this from http status code?
                  ...(typeof data === 'object' ? data : { data: data }),
                }),
              },
            ],
          }
        }
        throw error
      }
    })
  • Registers all MCP tools dynamically, generating names like 'API-{operationId}' from OpenAPI spec for listing.
    this.server.setRequestHandler(ListToolsRequestSchema, async () => {
      const tools: Tool[] = []
    
      // Add methods as separate tools to match the MCP format
      Object.entries(this.tools).forEach(([toolName, def]) => {
        def.methods.forEach(method => {
          const toolNameWithMethod = `${toolName}-${method.name}`;
          const truncatedToolName = this.truncateToolName(toolNameWithMethod);
          tools.push({
            name: truncatedToolName,
            description: method.description,
            inputSchema: method.inputSchema as Tool['inputSchema'],
          })
        })
      })
    
      return { tools }
    })
  • Generates MCP tool definition (schema, name 'API-{operationId}', description) from OpenAPI operation for tools like 'API-post-database-query'.
    const mcpMethod = this.convertOperationToMCPMethod(operation, method, path)
    if (mcpMethod) {
      const uniqueName = this.ensureUniqueName(mcpMethod.name)
      mcpMethod.name = uniqueName
      mcpMethod.description = this.getDescription(operation.summary || operation.description || '')
      tools[apiName]!.methods.push(mcpMethod)
      openApiLookup[apiName + '-' + uniqueName] = { ...operation, method, path }
      zip[apiName + '-' + uniqueName] = { openApi: { ...operation, method, path }, mcp: mcpMethod }
    }
  • Executes the actual HTTP request for the resolved OpenAPI operation, handling parameters, file uploads, and responses.
    async executeOperation<T = any>(
      operation: OpenAPIV3.OperationObject & { method: string; path: string },
      params: Record<string, any> = {},
    ): Promise<HttpClientResponse<T>> {
      const api = await this.api
      const operationId = operation.operationId
      if (!operationId) {
        throw new Error('Operation ID is required')
      }
    
      // Handle file uploads if present
      const formData = await this.prepareFileUpload(operation, params)
    
      // Separate parameters based on their location
      const urlParameters: Record<string, any> = {}
      const bodyParams: Record<string, any> = formData || { ...params }
    
      // Extract path and query parameters based on operation definition
      if (operation.parameters) {
        for (const param of operation.parameters) {
          if ('name' in param && param.name && param.in) {
            if (param.in === 'path' || param.in === 'query') {
              if (params[param.name] !== undefined) {
                urlParameters[param.name] = params[param.name]
                if (!formData) {
                  delete bodyParams[param.name]
                }
              }
            }
          }
        }
      }
    
      // Add all parameters as url parameters if there is no requestBody defined
      if (!operation.requestBody && !formData) {
        for (const key in bodyParams) {
          if (bodyParams[key] !== undefined) {
            urlParameters[key] = bodyParams[key]
            delete bodyParams[key]
          }
        }
      }
    
      const operationFn = (api as any)[operationId]
      if (!operationFn) {
        throw new Error(`Operation ${operationId} not found`)
      }
    
      try {
        // If we have form data, we need to set the correct headers
        const hasBody = Object.keys(bodyParams).length > 0
        const headers = formData
          ? formData.getHeaders()
          : { ...(hasBody ? { 'Content-Type': 'application/json' } : { 'Content-Type': null }) }
        const requestConfig = {
          headers: {
            ...headers,
          },
        }
    
        // first argument is url parameters, second is body parameters
        const response = await operationFn(urlParameters, hasBody ? bodyParams : undefined, requestConfig)
    
        // Convert axios headers to Headers object
        const responseHeaders = new Headers()
        Object.entries(response.headers).forEach(([key, value]) => {
          if (value) responseHeaders.append(key, value.toString())
        })
    
        return {
          data: response.data,
          status: response.status,
          headers: responseHeaders,
        }
      } catch (error: any) {
        if (error.response) {
          console.error('Error in http client', error)
          const headers = new Headers()
          Object.entries(error.response.headers).forEach(([key, value]) => {
            if (value) headers.append(key, value.toString())
          })
    
          throw new HttpClientError(error.response.statusText || 'Request failed', error.response.status, error.response.data, headers)
        }
        throw error
      }
    }
  • Initializes the tool definitions and lookup by converting the provided OpenAPI spec to MCP tools.
    const converter = new OpenAPIToMCPConverter(openApiSpec)
    const { tools, openApiLookup } = converter.convertToMCPTools()
    this.tools = tools
    this.openApiLookup = openApiLookup
Behavior2/5

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

With no annotations, the description carries full burden but provides minimal behavioral insight. It doesn't disclose if this is a read-only operation, requires authentication, has rate limits, or what the response format includes (e.g., pagination details). The term 'Query' suggests non-destructive reads, but this isn't explicitly confirmed, missing key context for safe usage.

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 extremely concise with 'Notion | Query a database', which is front-loaded and wastes no words. However, it may be overly terse, risking under-specification for a complex tool with 8 parameters, though it efficiently states the core action and platform.

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 tool's complexity (8 parameters, nested objects, no output schema, and no annotations), the description is incomplete. It doesn't explain return values, error conditions, or behavioral traits, leaving significant gaps for an AI agent to infer usage. Without annotations or output schema, more detail is needed to ensure proper tool invocation.

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 75%, providing good documentation for most parameters like database_id, filter, and page_size. The description adds no additional parameter semantics beyond the schema, but with high coverage, the baseline is 3. It doesn't compensate for gaps in parameters like archived or in_trash, which lack descriptions in both schema and tool description.

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

Purpose3/5

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

The description 'Notion | Query a database' states the platform and resource but is vague about the action—'Query' could mean search, filter, or retrieve, and it doesn't specify if this is for listing, filtering, or paginating database entries. It distinguishes from siblings like API-create-a-database or API-retrieve-a-database by implying read operations, but lacks clarity on exact functionality compared to API-post-search.

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?

No explicit guidance on when to use this tool versus alternatives is provided. The description doesn't mention when to choose this over API-post-search for broader searches or API-retrieve-a-database for metadata. Usage is implied through the name and parameters but not stated, leaving gaps for agent decision-making.

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

Related 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/gendosu/notion-mcp-server'

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