Skip to main content
Glama

read_pubnub_sdk_docs

Retrieve PubNub SDK documentation for specific programming languages and API reference sections. Provides code examples, usage patterns, and low-level API details in markdown format.

Instructions

Retrieves official PubNub SDK documentation for a given programming language and API reference section. Call this tool for low-level API details, code examples, and usage patterns. Returns documentation in markdown format. For conceptual guides, best practices, and how-tos, also call the read_pubnub_resources tool.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
apiReferenceNoAPI reference section to retrieve (e.g. configuration, publish-and-subscribe, objects (App Context); defaults to configuration)configuration
languageYesProgramming language of the PubNub SDK to retrieve documentation for (e.g. javascript, python)

Implementation Reference

  • Main execution handler for read_pubnub_sdk_docs tool. Handles parameters language and apiReference, loads from cache or fetches SDK docs from PubNub site, combines with additional resources, and returns markdown content.
    toolHandlers['read_pubnub_sdk_docs'] = async ({ language, apiReference }) => {
        const apiRefKey = apiReference === 'App Context' ? 'objects' : apiReference;
        // Early return for PubNub Functions documentation
        if (apiRefKey === 'functions') {
          try {
            const functionsDoc = fs.readFileSync(
              pathJoin(__dirname, 'resources', 'pubnub_functions.md'),
              'utf8'
            );
            return { content: [ { type: 'text', text: functionsDoc } ] };
          } catch (err) {
            return {
              content: [ { type: 'text', text: `Error loading functions documentation: ${err}` } ],
              isError: true
            };
          }
        }
    
        // Special case for rest-api - load only the three specific files
        if (language === 'rest-api') {
          const restApiFiles = [
            'rest-api_publish-message-to-channel.md',
            'rest-api_subscribe-v-2.md',
            'rest-api_get-message-history.md'
          ];
          
          let combinedRestApiContent = '';
          
          for (const filename of restApiFiles) {
            try {
              const filePath = pathJoin(__dirname, 'resources', 'sdk_docs', filename);
              const content = fs.readFileSync(filePath, 'utf8');
              combinedRestApiContent += content + '\n\n';
            } catch (err) {
              //console.error(`Error loading ${filename}: ${err}`);
              combinedRestApiContent += `Error loading ${filename}: ${err.message}\n\n`;
            }
          }
          
          return {
            content: [
              {
                type: 'text',
                text: combinedRestApiContent + getPubNubInitSDKInstructions(),
              },
            ],
          };
        }
    
        // Regular processing for other languages
        // Try to load from cached files first (with version checking), fallback to API calls if not available or outdated
        let sdkResponse = loadCachedSDKDoc(language, 'overview');
        if (!sdkResponse) {
          const sdkURL = `https://www.pubnub.com/docs/sdks/${language}`;
          sdkResponse = await loadArticle(sdkURL);
        }
    
        let apiRefResponse = loadCachedSDKDoc(language, apiRefKey);
        if (!apiRefResponse) {
          const apiRefURL = `https://www.pubnub.com/docs/sdks/${language}/api-reference/${apiRefKey}`;
          apiRefResponse = await loadArticle(apiRefURL);
    
          // Apply "(old)" section removal logic for dynamically loaded content
          if (apiRefResponse && !apiRefResponse.startsWith('Error fetching')) {
            const lines = apiRefResponse.split('\n');
            const oldIndex = lines.findIndex((line) => /^##\s.*\(old\)/i.test(line));
            if (oldIndex !== -1) {
              apiRefResponse = lines.slice(0, oldIndex).join('\n');
            }
          }
        }
    
        const context7Response = loadLanguageFile(language);
        const presenceBestPracticesResponse = loadPresenceBestPracticesFile(language);
    
        // Combine the content of both responses
        const combinedContent = [sdkResponse, apiRefResponse, context7Response, presenceBestPracticesResponse].join('\n\n');
    
        // Return the combined content
        return {
          content: [
            {
              type: 'text',
              text: combinedContent + getPubNubInitSDKInstructions(),
            },
          ],
        };
    };
  • Zod schema and metadata definition for the read_pubnub_sdk_docs tool, including name, description, and input parameters (language enum and optional apiReference).
    toolDefinitions['read_pubnub_sdk_docs'] = {
      name: 'read_pubnub_sdk_docs',
      description: 'Retrieves official PubNub SDK documentation for a given programming language and API reference section. Call this tool for low-level API details, code examples, and usage patterns. Returns documentation in markdown format. For conceptual guides, best practices, and how-tos, also call the read_pubnub_resources tool.',
      parameters: {
        language: z.enum(languages).describe('Programming language of the PubNub SDK to retrieve documentation for (e.g. javascript, python)'),
        apiReference: z.enum(apiReferences).optional().default('configuration').describe('API reference section to retrieve (e.g. configuration, publish-and-subscribe, objects (App Context); defaults to configuration)'),
      }
    };
  • index.js:1363-1394 (registration)
    Registration function that adds the read_pubnub_sdk_docs tool to the MCP server using server.tool(). Excludes it when chatSdkMode is true. Called for main server and HTTP session servers.
    function registerAllTools(serverInstance, chatSdkMode = false) {
      // Tools to exclude when in chat SDK mode
      const chatSdkExcludedTools = [
        'read_pubnub_sdk_docs',
        'write_pubnub_app', 
        'read_pubnub_resources',
        'manage_pubnub_account'
      ];
    
      for (const toolName in toolDefinitions) {
        if (toolHandlers[toolName]) {
          // Skip excluded tools when in chat SDK mode
          if (chatSdkMode && chatSdkExcludedTools.includes(toolName)) {
            continue;
          }
    
          // Special handling for chat SDK docs tool
          if (toolName === 'read_pubnub_chat_sdk_docs' && 
              (chatSdkLanguages.length === 0 || chatSdkTopics.length === 0)) {
            continue; // Skip this tool if chat SDK data isn't loaded
          }
          
          const toolDef = toolDefinitions[toolName];
          serverInstance.tool(
            toolDef.name,
            toolDef.description,
            toolDef.parameters,
            wrapToolHandler(toolHandlers[toolName], toolName)
          );
        }
      }
    }
  • Helper function to load cached SDK documentation from resources/sdk_docs directory, with version checking to determine if fresh fetch is needed.
    function loadCachedSDKDoc(language, type, forceRefresh = false) {
      try {
        const filename = `${sanitizeFilename(language)}_${sanitizeFilename(type)}.md`;
        const filePath = pathJoin(__dirname, 'resources', 'sdk_docs', filename);
        
        // Check if file exists
        if (!fs.existsSync(filePath)) {
          return null;
        }
        
        const content = fs.readFileSync(filePath, 'utf8');
        
        // Skip version checking if force refresh is requested or for REST API
        if (forceRefresh || language === 'rest-api') {
          return content;
        }
        
        // Extract version from cached content
        const cachedVersion = extractVersionFromCachedDoc(content);
        const currentVersion = sdkVersions[language];
        
        // If we have both versions and they match, return cached content
        if (cachedVersion && currentVersion && isVersionMatch(cachedVersion, currentVersion)) {
          return content;
        }
        
        // If versions don't match or we can't determine versions, return null to trigger fresh fetch
        if (cachedVersion && currentVersion && !isVersionMatch(cachedVersion, currentVersion)) {
          //console.log(`Version mismatch for ${language}: cached=${cachedVersion}, current=${currentVersion}. Will fetch fresh content.`);
        }
        
        return null;
      } catch (err) {
        //console.error(`Error loading cached SDK doc ${language}_${type}: ${err}`);
        return null;
      }
    }
Behavior3/5

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

No annotations are provided, so the description carries the full burden. It discloses the return format ('Returns documentation in markdown format'), which is useful behavioral context. However, it lacks details on potential errors, rate limits, or authentication requirements, leaving gaps for a tool that retrieves documentation.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is appropriately sized and front-loaded, with three sentences that each add value: the first states the purpose, the second provides usage guidelines, and the third clarifies the return format and sibling differentiation. There is no wasted text.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness4/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the tool's low complexity (2 parameters, no output schema, no annotations), the description is mostly complete. It covers purpose, usage guidelines, return format, and sibling differentiation. However, without annotations or an output schema, it could benefit from more behavioral details (e.g., error handling), but it's sufficient for a documentation retrieval tool.

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 100%, so the schema already documents both parameters thoroughly with enums and defaults. The description adds no additional parameter semantics beyond what the schema provides, such as explaining the relationship between language and API reference sections. Baseline 3 is appropriate when the schema does the heavy lifting.

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

Purpose5/5

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

The description clearly states the tool's purpose with specific verbs ('retrieves') and resources ('official PubNub SDK documentation'), and explicitly distinguishes it from its sibling tool (read_pubnub_resources) by specifying it's for 'low-level API details, code examples, and usage patterns' versus 'conceptual guides, best practices, and how-tos'.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines5/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides explicit guidance on when to use this tool ('Call this tool for low-level API details, code examples, and usage patterns') and when to use an alternative ('For conceptual guides, best practices, and how-tos, also call the read_pubnub_resources tool'), clearly differentiating it from its sibling.

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/pubnub/pubnub-mcp-server'

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