Skip to main content
Glama

API-retrieve-a-database

Retrieve structured data from a Notion database using its ID to access content through read-only queries for AI assistants.

Instructions

Retrieve a database

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
database_idYesAn identifier for the Notion database.

Implementation Reference

  • Registers all converted OpenAPI operations as MCP tools, including 'API-retrieve-a-database' (toolName='API', method.name='retrieve-a-database').
    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'],
        })
        console.log(`- ${truncatedToolName}: ${method.description}`)
      })
    })
  • Generic handler for tool calls: looks up OpenAPI operation for tool name 'API-retrieve-a-database', executes HTTP request via httpClient, updates cache, and returns JSON response.
    // Find the operation in OpenAPI spec
    const operation = this.findOperation(name)
    if (!operation) {
      const error = `Method ${name} not found.`
      console.error(error)
      return {
        content: [
          {
            type: 'text',
            text: JSON.stringify({
              status: 'error',
              message: error,
              code: 404
            }),
          },
        ],
      }
    }
    
    // Optimized parallel processing for API-get-block-children
    if (name === 'API-get-block-children') {
      // Create basic options for logging control
      const blockOptions: RecursiveExplorationOptions = {
        runInBackground: false, // Default to not showing logs for regular API calls
      };
      
      return await this.handleBlockChildrenParallel(operation, params, blockOptions);
    }
    
    // Other regular API calls
    console.log(`Notion API call: ${operation.method.toUpperCase()} ${operation.path}`)
    const response = await this.httpClient.executeOperation(operation, params)
    
    // Log response summary
    console.log('Notion API response code:', response.status)
    if (response.status !== 200) {
      console.error('Response error:', response.data)
    } else {
      console.log('Response success')
    }
    
    // Update cache with response data
    this.updateCacheFromResponse(name, response.data);
    
    // Convert response to MCP format
    return {
      content: [
        {
          type: 'text',
          text: JSON.stringify(response.data),
        },
      ],
    }
  • Updates the database cache after a successful API-retrieve-a-database call.
    private updateCacheFromResponse(apiName: string, data: any): void {
      if (!data || typeof data !== 'object') return;
    
      try {
        // Update appropriate cache based on API response type
        if (apiName === 'API-retrieve-a-page' && data.object === 'page' && data.id) {
          this.pageCache.set(data.id, data);
        } else if (apiName === 'API-retrieve-a-block' && data.object === 'block' && data.id) {
          this.blockCache.set(data.id, data);
        } else if (apiName === 'API-retrieve-a-database' && data.object === 'database' && data.id) {
          this.databaseCache.set(data.id, data);
        } else if (apiName === 'API-retrieve-a-comment' && data.results) {
          // Cache comments from result list
          data.results.forEach((comment: any) => {
            if (comment.object === 'comment' && comment.id) {
              this.commentCache.set(comment.id, comment);
            }
          });
        } else if (apiName === 'API-retrieve-a-page-property' && data.results) {
          // Page property caching - would need params from call context
          // Skip this in current context
          console.log('Page property information has been cached');
        }
    
        // API-get-block-children handled in handleBlockChildrenParallel
      } catch (error) {
        console.warn('Error updating cache:', error);
      }
    }
  • Helper method used internally to retrieve Notion database details using the API-retrieve-a-database tool, with caching.
    private async retrieveDatabase(databaseId: string, options: RecursiveExplorationOptions): Promise<any> {
      console.log(`Retrieving database information: ${databaseId}`);
      
      // Check cache
      if (!options.skipCache && this.databaseCache.has(databaseId)) {
        console.log(`Database cache hit: ${databaseId}`);
        return this.databaseCache.get(databaseId);
      }
      
      // Get database info via API call
      const operation = this.findOperation('API-retrieve-a-database');
      if (!operation) {
        console.warn('API-retrieve-a-database method not found.');
        return { id: databaseId, note: "Database details not available" };
      }
      
      try {
        console.log(`Notion API call: ${operation.method.toUpperCase()} ${operation.path} (databaseId: ${databaseId})`);
        const response = await this.httpClient.executeOperation(operation, { database_id: databaseId });
        
        if (response.status !== 200) {
          console.error('Error retrieving database information:', response.data);
          return { id: databaseId, error: "Failed to retrieve database" };
        }
        
        const databaseData = response.data;
        this.databaseCache.set(databaseId, databaseData);
        return databaseData;
      } catch (error) {
        console.error('Error retrieving database:', error);
        return { id: databaseId, error: "Failed to retrieve database" };
      }
    }
  • Initializes the tools map including 'API-retrieve-a-database' by converting the OpenAPI specification using OpenAPIToMCPConverter.
      const converter = new OpenAPIToMCPConverter(openApiSpec)
      const { tools, openApiLookup } = converter.convertToMCPTools()
      this.tools = tools
      this.openApiLookup = openApiLookup
    
      this.setupHandlers()
    }

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/Taewoong1378/notion-readonly-mcp-server'

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