Skip to main content
Glama
YuheiNakasaka

Scrapbox MCP Server

get_page_content

Fetch content from a Scrapbox page using its URL to access and retrieve note information.

Instructions

Fetch content from a Scrapbox page by URL

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
urlYesScrapbox page URL (e.g., https://scrapbox.io/project-name/page-title)

Implementation Reference

  • Handler for the get_page_content tool. Validates input, extracts Scrapbox project and page from URL, fetches content from Scrapbox API, formats it, and returns as text content block. Handles errors appropriately.
    server.setRequestHandler(CallToolRequestSchema, async (request) => {
      console.error("[Tool] Called:", request.params.name);
      
      if (request.params.name !== "get_page_content") {
        throw new McpError(
          ErrorCode.MethodNotFound,
          `Unknown tool: ${request.params.name}`
        );
      }
      
      if (!isValidGetPageContentArgs(request.params.arguments)) {
        throw new McpError(
          ErrorCode.InvalidParams,
          "Invalid arguments: 'url' parameter is required and must be a string"
        );
      }
      
      try {
        const { url } = request.params.arguments;
        const { projectName, pageTitle } = extractScrapboxInfo(url);
        const content = await fetchScrapboxPage(projectName, pageTitle);
        
        return {
          content: [
            {
              type: "text",
              text: content
            }
          ]
        };
      } catch (error) {
        console.error("[Error] Tool execution failed:", error);
        
        if (error instanceof McpError) {
          return {
            content: [
              {
                type: "text",
                text: error.message
              }
            ],
            isError: true
          };
        }
        
        return {
          content: [
            {
              type: "text",
              text: `Error fetching Scrapbox content: ${error instanceof Error ? error.message : String(error)}`
            }
          ],
          isError: true
        };
      }
    });
  • TypeScript interface defining the input arguments for get_page_content tool (url: string) and validation function to check if arguments match the schema.
    interface GetPageContentArgs {
      url: string;
    }
    
    /**
     * Validates if the input is a valid GetPageContentArgs object
     */
    const isValidGetPageContentArgs = (args: any): args is GetPageContentArgs => {
      return typeof args === "object" && args !== null && typeof args.url === "string";
    };
  • src/index.ts:197-218 (registration)
    Registration of the get_page_content tool in the ListToolsRequestSchema handler. Specifies name, description, and JSON input schema requiring a 'url' string.
    server.setRequestHandler(ListToolsRequestSchema, async () => {
      console.error("[Setup] Registering tools");
      
      return {
        tools: [
          {
            name: "get_page_content",
            description: "Fetch content from a Scrapbox page by URL",
            inputSchema: {
              type: "object",
              properties: {
                url: {
                  type: "string",
                  description: "Scrapbox page URL (e.g., https://scrapbox.io/project-name/page-title)"
                }
              },
              required: ["url"]
            }
          }
        ]
      };
    });
  • Helper function that fetches Scrapbox page data via API, formats title, descriptions, lines (content), and metadata into Markdown string.
    async function fetchScrapboxPage(projectName: string, pageTitle: string): Promise<string> {
      const apiUrl = `https://scrapbox.io/api/pages/${encodeURIComponent(projectName)}/${encodeURIComponent(pageTitle)}`;
      console.error("[API] Request to endpoint:", apiUrl);
      
      try {
        const response = await axios.get<ScrapboxPage>(apiUrl);
        const page = response.data;
        
        // Format the page content
        let formattedContent = `# ${page.title}\n\n`;
        
        // Add descriptions if available
        if (page.descriptions && page.descriptions.length > 0) {
          formattedContent += "## 概要\n";
          formattedContent += page.descriptions.join("\n") + "\n\n";
        }
        
        // Add content from lines
        formattedContent += "## 内容\n";
        formattedContent += page.lines
          .slice(1) // Skip the first line (title)
          .map(line => line.text)
          .join("\n");
        
        // Add metadata
        formattedContent += "\n\n## メタデータ\n";
        formattedContent += `- 作成日時: ${new Date(page.created).toISOString()}\n`;
        formattedContent += `- 更新日時: ${new Date(page.updated).toISOString()}\n`;
        formattedContent += `- 閲覧数: ${page.views}\n`;
        formattedContent += `- リンク数: ${page.linked}\n`;
        
        return formattedContent;
      } catch (error) {
        console.error("[Error] API request failed:", error);
        
        if (axios.isAxiosError(error)) {
          if (error.response?.status === 404) {
            throw new McpError(
              ErrorCode.InvalidParams,
              "Page not found: The requested Scrapbox page does not exist"
            );
          }
          
          throw new McpError(
            ErrorCode.InternalError,
            `Scrapbox API error: ${error.response?.data?.message || error.message}`
          );
        }
        
        throw new McpError(
          ErrorCode.InternalError,
          `Failed to fetch Scrapbox page: ${error instanceof Error ? error.message : String(error)}`
        );
      }
    }
  • Helper function to parse a Scrapbox URL, validate it's scrapbox.io, extract project name and page title from path.
    function extractScrapboxInfo(url: string): { projectName: string; pageTitle: string } {
      console.error("[URL] Processing URL:", url);
      
      try {
        const urlObj = new URL(url);
        
        // Validate that this is a Scrapbox URL
        if (urlObj.hostname !== "scrapbox.io") {
          throw new McpError(
            ErrorCode.InvalidParams,
            "Invalid URL: Not a Scrapbox URL"
          );
        }
        
        // Extract project name and page title from path
        const pathParts = urlObj.pathname.split("/").filter(part => part);
        
        if (pathParts.length < 2) {
          throw new McpError(
            ErrorCode.InvalidParams,
            "Invalid URL format: Missing project name or page title"
          );
        }
        
        const projectName = pathParts[0];
        const pageTitle = decodeURIComponent(pathParts[1]);
        
        console.error("[URL] Extracted project:", projectName, "page:", pageTitle);
        
        return { projectName, pageTitle };
      } catch (error) {
        if (error instanceof McpError) {
          throw error;
        }
        
        console.error("[Error] URL parsing failed:", error);
        throw new McpError(
          ErrorCode.InvalidParams,
          `Invalid URL format: ${error instanceof Error ? error.message : String(error)}`
        );
      }
    }
Install Server

Other 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/YuheiNakasaka/scrapbox-mcp'

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