Skip to main content
Glama
DLHellMe

Telegram MCP Server

by DLHellMe

scrape_channel

Extract Telegram channel posts in markdown format for content analysis or archiving. Specify URL and post limit to gather channel data with optional reaction information.

Instructions

Scrape a Telegram channel and return posts in markdown format. Uses authenticated session if logged in.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
urlYesThe Telegram channel URL (e.g., https://t.me/channelname)
max_postsNoMaximum number of posts to scrape (default: 100)
include_reactionsNoInclude reaction data in the output

Implementation Reference

  • The primary handler function for the 'scrape_channel' tool. It checks authentication status, selects the appropriate scraper (authenticated or unauthenticated), prepares scrape options from tool arguments, invokes the scraper's scrape method, formats the result as markdown, and returns the MCP-standard content response with an authentication indicator if applicable.
    private async handleScrapeChannel(args: any): Promise<any> {
      // Check if authenticated and use authenticated scraper by default
      const isAuthenticated = await this.auth.isAuthenticated();
      const scraperToUse = isAuthenticated ? this.authScraper : this.scraper;
      
      if (isAuthenticated) {
        logger.info('Using authenticated scraper (logged in)');
      } else {
        logger.info('Using unauthenticated scraper (not logged in)');
      }
    
      const options: ScrapeOptions = {
        url: args.url,
        maxPosts: args.max_posts === undefined ? 0 : args.max_posts, // 0 means no limit
        includeReactions: args.include_reactions !== false
      };
    
      const result = await scraperToUse.scrape(options);
      const markdown = this.formatter.format(result);
    
      return {
        content: [
          {
            type: 'text',
            text: isAuthenticated 
              ? `${markdown}\n\nāœ… *Scraped using authenticated session*`
              : markdown
          }
        ]
      };
    }
  • src/server.ts:124-146 (registration)
    Registers the 'scrape_channel' tool with the MCP server via the getTools() method, providing name, description, and input schema for validation.
      name: 'scrape_channel',
      description: 'Scrape a Telegram channel and return posts in markdown format. Uses authenticated session if logged in.',
      inputSchema: {
        type: 'object',
        properties: {
          url: {
            type: 'string',
            description: 'The Telegram channel URL (e.g., https://t.me/channelname)'
          },
          max_posts: {
            type: 'number',
            description: 'Maximum number of posts to scrape (default: 100)',
            default: 100
          },
          include_reactions: {
            type: 'boolean',
            description: 'Include reaction data in the output',
            default: true
          }
        },
        required: ['url']
      }
    },
  • Input schema definition for the 'scrape_channel' tool, specifying parameters like url (required), max_posts, and include_reactions with types, descriptions, and defaults.
    inputSchema: {
      type: 'object',
      properties: {
        url: {
          type: 'string',
          description: 'The Telegram channel URL (e.g., https://t.me/channelname)'
        },
        max_posts: {
          type: 'number',
          description: 'Maximum number of posts to scrape (default: 100)',
          default: 100
        },
        include_reactions: {
          type: 'boolean',
          description: 'Include reaction data in the output',
          default: true
        }
      },
      required: ['url']
  • Core helper function implementing the scraping logic called by the handler. Handles browser page creation, URL validation/navigation (auth/unauth modes), channel info parsing, infinite scrolling to collect posts with deduplication and limits, error handling with screenshots, file saving, and returns structured ScrapeResult.
    async scrape(options: ScrapeOptions): Promise<ScrapeResult> {
      logger.info(`Starting scrape for: ${options.url}`);
      
      let page: Page | null = null;
      
      try {
        // Validate URL
        if (!this.isValidTelegramUrl(options.url)) {
          throw new Error('Invalid Telegram URL. Must be a t.me link.');
        }
    
        // Create page
        page = await this.browserManager.createPage();
        
        // Navigate to channel/group
        await this.navigateToChannel(page, options.url);
        
        // Get channel info BEFORE scrolling
        const channelHtml = await page.content();
        const parser = new DataParser(channelHtml);
        let channel = parser.parseChannelInfo();
        
        // Try to get channel name and username from URL if parsing failed
        const urlMatch = options.url.match(/t\.me\/s?\/([^/?]+)/);
        if (urlMatch && urlMatch[1]) {
          if (channel.username === 'unknown') {
            channel.username = urlMatch[1];
          }
          if (channel.name === 'Unknown Channel') {
            channel.name = urlMatch[1];
          }
        }
        
        // Scroll and collect posts
        const posts = await this.scrollAndCollectPosts(page, options);
        
        // Get total post count from collected posts
        const totalPosts = posts.length;
        
        logger.info(`Scraping complete. Total posts: ${totalPosts}`);
        
        const result = {
          channel,
          posts,
          scrapedAt: new Date(),
          totalPosts
        };
        
        // Save to file
        await this.saveToFile(result, channel.username);
        
        return result;
        
      } catch (error) {
        logger.error('Scraping failed:', error);
        
        // Take screenshot on error
        if (page && config.debug.saveScreenshots) {
          await this.browserManager.screenshot(page, 'error');
        }
        
        return {
          channel: {
            name: 'Unknown',
            username: 'unknown',
            description: ''
          },
          posts: [],
          scrapedAt: new Date(),
          totalPosts: 0,
          error: error instanceof Error ? error.message : 'Unknown error'
        };
        
      } finally {
        if (page) {
          await page.close();
        }
      }
    }

Schema Changelog

Changes observed during successful MCP inspections.

  1. First observed

TDQS

B3.1/5.0
Behavior2/5

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

No annotations are provided, so the description bears full responsibility for behavioral disclosure. It does note that it uses an authenticated session if logged in, which is a useful behavioral trait. However, it lacks details about error behavior, rate limits, output structure beyond 'markdown', or what happens when not authenticated. This is a minimal disclosure.

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 two sentences and highly concise. It front-loads the core action ('Scrape a Telegram channel') and immediately adds the return format and an important behavioral condition (authenticated session). Every word adds value with no redundancy.

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

Completeness3/5

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

Given the lack of an output schema, the description does mention the return format (markdown). There are three well-described parameters and no nested objects, so the core usage is covered. However, the absence of usage guidelines relative to many sibling tools and limited behavioral context makes the description only minimally complete for an agent to select this tool appropriately.

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 baseline is 3. The description does not add any additional meaning to the parameters themselves. Since each parameter already has a clear schema description, the tool description does not need to compensate further.

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

Purpose4/5

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

The description clearly states the tool's function: scrape a Telegram channel and return posts in markdown format. It uses a specific verb ('scrape') and resource ('Telegram channel'), which differentiates it from siblings like get_channel_info. However, it does not distinguish itself from closely related tools such as scrape_channel_full or scrape_channel_authenticated.

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?

The description provides no guidance on when to use this tool versus alternatives. It mentions the authenticated session condition but does not specify when to choose scrape_channel over scrape_channel_full, scrape_channel_authenticated, or api_scrape_channel. There are no exclusions or explicit context.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.