@kagayoi/hatena-blog-mcp 0.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,159 @@
1
+ import { XMLParser } from "fast-xml-parser";
2
+ import { AtomPubError } from "../atompub/errors.js";
3
+ import { MAX_IMAGE_BASE64_CHARS, MAX_IMAGE_BYTES } from "../utils/limits.js";
4
+ import { assertValidXmlChars } from "../utils/xml.js";
5
+ import type { FotolifeImage, FotolifeUploadPayload } from "./types.js";
6
+
7
+ type XmlNode = Record<string, unknown>;
8
+
9
+ const parser = new XMLParser({
10
+ ignoreAttributes: false,
11
+ attributeNamePrefix: "@_",
12
+ parseTagValue: false,
13
+ parseAttributeValue: false,
14
+ trimValues: false,
15
+ processEntities: true,
16
+ htmlEntities: true,
17
+ removeNSPrefix: true,
18
+ textNodeName: "#text",
19
+ isArray: (name) => {
20
+ const localName = name.split(":").at(-1) ?? name;
21
+ return localName === "entry" || localName === "link";
22
+ },
23
+ });
24
+
25
+ function parse(xml: string): XmlNode {
26
+ try {
27
+ return parser.parse(xml) as XmlNode;
28
+ } catch (cause) {
29
+ throw new AtomPubError("Failed to parse Fotolife XML", {
30
+ status: 0,
31
+ code: "parse_error",
32
+ body: xml.slice(0, 500),
33
+ cause,
34
+ });
35
+ }
36
+ }
37
+
38
+ function asObject(value: unknown): XmlNode {
39
+ if (value === null || value === undefined || typeof value !== "object") return {};
40
+ return value as XmlNode;
41
+ }
42
+
43
+ function asArray<T>(value: T | T[] | undefined): T[] {
44
+ if (value === undefined) return [];
45
+ return Array.isArray(value) ? value : [value];
46
+ }
47
+
48
+ function asString(value: unknown): string | undefined {
49
+ if (typeof value === "string") return value;
50
+ if (value !== null && typeof value === "object") {
51
+ const text = (value as XmlNode)["#text"];
52
+ if (typeof text === "string") return text;
53
+ }
54
+ return undefined;
55
+ }
56
+
57
+ function escapeText(value: string): string {
58
+ assertValidXmlChars(value);
59
+ return value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
60
+ }
61
+
62
+ function escapeAttr(value: string): string {
63
+ return escapeText(value).replace(/"/g, "&quot;").replace(/'/g, "&apos;");
64
+ }
65
+
66
+ function normalizeBlogSyntax(syntax: string): string {
67
+ const bare = syntax
68
+ .replace(/^\[/, "")
69
+ .replace(/\]$/, "")
70
+ .replace(/:image$/, ":plain");
71
+ return `[${bare}]`;
72
+ }
73
+
74
+ function photoFromNode(node: XmlNode): FotolifeImage {
75
+ const links = asArray(node.link as XmlNode | XmlNode[] | undefined);
76
+ let pageUrl: string | undefined;
77
+ let editUrl: string | undefined;
78
+ for (const link of links) {
79
+ const rel = link["@_rel"];
80
+ const href = link["@_href"];
81
+ if (typeof href !== "string") continue;
82
+ if (rel === "alternate") pageUrl = href;
83
+ if (rel === "service.edit" || rel === "edit") editUrl = href;
84
+ }
85
+
86
+ const syntax = asString(node.syntax) ?? "";
87
+ const idFromEdit = editUrl ? /\/atom\/edit\/([^/?#]+)/.exec(editUrl)?.[1] : undefined;
88
+ const idFromSyntax = /:([0-9]+)[a-z]?:/.exec(syntax)?.[1];
89
+ const id = idFromEdit ?? idFromSyntax ?? "";
90
+ const imageUrl = asString(node.imageurl) ?? "";
91
+ if (!id || !syntax || !imageUrl) {
92
+ throw new AtomPubError("Fotolife response is missing required image fields", {
93
+ status: 0,
94
+ code: "parse_error",
95
+ });
96
+ }
97
+
98
+ return {
99
+ id,
100
+ title: asString(node.title) ?? "",
101
+ syntax,
102
+ blogSyntax: normalizeBlogSyntax(syntax),
103
+ imageUrl,
104
+ ...(asString(node.imageurlsmall) !== undefined
105
+ ? { imageUrlSmall: asString(node.imageurlsmall) as string }
106
+ : {}),
107
+ ...(pageUrl !== undefined ? { pageUrl } : {}),
108
+ ...(editUrl !== undefined ? { editUrl } : {}),
109
+ ...(asString(node.subject) !== undefined ? { folder: asString(node.subject) as string } : {}),
110
+ ...(asString(node.issued) !== undefined ? { issued: asString(node.issued) as string } : {}),
111
+ };
112
+ }
113
+
114
+ export function normalizeImageBase64(data: string): string {
115
+ if (data.length > MAX_IMAGE_BASE64_CHARS) {
116
+ throw new Error(`画像は${MAX_IMAGE_BYTES / 1024 / 1024} MiB以下にしてください。`);
117
+ }
118
+ const compact = data.replace(/\s+/g, "");
119
+ if (!compact) throw new Error("画像のbase64データが空です。");
120
+ if (
121
+ compact.length % 4 !== 0 ||
122
+ !/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(compact)
123
+ ) {
124
+ throw new Error("画像のbase64データが不正です。");
125
+ }
126
+ const padding = compact.endsWith("==") ? 2 : compact.endsWith("=") ? 1 : 0;
127
+ const decodedBytes = (compact.length / 4) * 3 - padding;
128
+ if (decodedBytes > MAX_IMAGE_BYTES) {
129
+ throw new Error(`画像は${MAX_IMAGE_BYTES / 1024 / 1024} MiB以下にしてください。`);
130
+ }
131
+ return compact;
132
+ }
133
+
134
+ export function buildFotolifeUploadXml(payload: FotolifeUploadPayload): string {
135
+ const data = normalizeImageBase64(payload.dataBase64);
136
+ const folder = payload.folder ?? "Hatena Blog";
137
+ const generator = payload.generator ?? "hatena-blog-mcp";
138
+ return (
139
+ '<entry xmlns="http://purl.org/atom/ns#" xmlns:dc="http://purl.org/dc/elements/1.1/">' +
140
+ `<title>${escapeText(payload.title)}</title>` +
141
+ `<content mode="base64" type="${escapeAttr(payload.contentType)}">${data}</content>` +
142
+ `<dc:subject>${escapeText(folder)}</dc:subject>` +
143
+ `<generator>${escapeText(generator)}</generator>` +
144
+ "</entry>"
145
+ );
146
+ }
147
+
148
+ export function parseFotolifeImage(xml: string): FotolifeImage {
149
+ const doc = parse(xml);
150
+ const raw = doc.entry;
151
+ const entry = Array.isArray(raw) ? raw[0] : raw;
152
+ if (!entry || typeof entry !== "object") {
153
+ throw new AtomPubError("Expected <entry> root element for Fotolife image", {
154
+ status: 0,
155
+ code: "parse_error",
156
+ });
157
+ }
158
+ return photoFromNode(asObject(entry));
159
+ }
package/src/index.ts ADDED
@@ -0,0 +1,3 @@
1
+ /// <reference path="./worker-configuration.d.ts" />
2
+
3
+ export { createApp, default } from "./adapters/cloudflare/index.js";
@@ -0,0 +1,48 @@
1
+ import { AtomPubClient } from "../atompub/client.js";
2
+ import type { BasicCredentials } from "../utils/auth.js";
3
+ import type { RetryOptions } from "../utils/retry.js";
4
+
5
+ /**
6
+ * Everything a tool handler needs to talk to Hatena on behalf of the caller.
7
+ *
8
+ * Constructed once per MCP request in the transport adapter so that every
9
+ * tool invocation inside that request sees the same credentials. The
10
+ * adapter is responsible for extracting `credentials` from the
11
+ * `Authorization` header and rejecting unauthenticated requests before the
12
+ * tool layer ever runs.
13
+ */
14
+ export interface ToolContext {
15
+ credentials: BasicCredentials;
16
+ fetchImpl?: typeof fetch;
17
+ retry?: RetryOptions;
18
+ signal?: AbortSignal;
19
+ requestTimeoutMs?: number;
20
+ requestId?: string;
21
+ }
22
+
23
+ /**
24
+ * Builds a scoped AtomPubClient for a specific blog.
25
+ *
26
+ * `hatenaIdOverride` lets a tool call target a blog owned by a different
27
+ * Hatena ID than the credential's username component — only meaningful if
28
+ * the same API key happens to be valid for both accounts (rare but
29
+ * technically possible for group blogs).
30
+ */
31
+ export function makeClient(
32
+ ctx: ToolContext,
33
+ blogId: string,
34
+ hatenaIdOverride?: string,
35
+ ): AtomPubClient {
36
+ const opts: ConstructorParameters<typeof AtomPubClient>[0] = {
37
+ credentials: {
38
+ authHeader: ctx.credentials.authHeader,
39
+ hatenaId: hatenaIdOverride ?? ctx.credentials.hatenaId,
40
+ },
41
+ blogId,
42
+ };
43
+ if (ctx.fetchImpl) opts.fetchImpl = ctx.fetchImpl;
44
+ if (ctx.retry) opts.retry = ctx.retry;
45
+ if (ctx.signal) opts.signal = ctx.signal;
46
+ if (ctx.requestTimeoutMs !== undefined) opts.requestTimeoutMs = ctx.requestTimeoutMs;
47
+ return new AtomPubClient(opts);
48
+ }
@@ -0,0 +1,82 @@
1
+ import { AtomPubError } from "../atompub/errors.js";
2
+
3
+ export interface ToolTextResult {
4
+ [key: string]: unknown;
5
+ content: Array<{ type: "text"; text: string }>;
6
+ structuredContent?: Record<string, unknown>;
7
+ isError?: boolean;
8
+ }
9
+
10
+ export interface ToolErrorMeta {
11
+ operation: string;
12
+ requestId?: string | undefined;
13
+ }
14
+
15
+ /**
16
+ * Wrap a JSON-serialisable payload as an MCP tool result.
17
+ *
18
+ * `structuredContent` is the machine-readable channel; the text content
19
+ * carries the same JSON so clients that don't support structuredContent yet
20
+ * (or that display tool output as plain text) still show something useful.
21
+ */
22
+ export function ok(payload: Record<string, unknown>): ToolTextResult {
23
+ const text = JSON.stringify(payload, null, 2);
24
+ return {
25
+ content: [{ type: "text", text }],
26
+ structuredContent: payload,
27
+ };
28
+ }
29
+
30
+ /**
31
+ * Map an AtomPubError to a user-facing Japanese message (as specified in the
32
+ * tool spec). The raw response body and stack trace are intentionally dropped
33
+ * from the client-facing result and logs. Operators receive only structured,
34
+ * sanitised metadata suitable for correlation.
35
+ */
36
+ export function toolError(
37
+ err: unknown,
38
+ meta: ToolErrorMeta = { operation: "unknown" },
39
+ ): ToolTextResult {
40
+ const log: Record<string, unknown> = {
41
+ tag: "tool-error",
42
+ operation: meta.operation,
43
+ category: err instanceof AtomPubError ? err.code : "unexpected",
44
+ };
45
+ if (meta.requestId !== undefined) log.requestId = meta.requestId;
46
+ if (err instanceof AtomPubError && err.status > 0) log.status = err.status;
47
+ if (err instanceof Error) log.errorName = err.name;
48
+ console.error(JSON.stringify(log));
49
+
50
+ const message = formatErrorMessage(err);
51
+ return {
52
+ content: [{ type: "text", text: message }],
53
+ isError: true,
54
+ };
55
+ }
56
+
57
+ function formatErrorMessage(err: unknown): string {
58
+ if (err instanceof AtomPubError) {
59
+ switch (err.code) {
60
+ case "unauthorized":
61
+ return "認証に失敗しました。APIキーを確認してください。";
62
+ case "forbidden":
63
+ return "操作が許可されていません (403)。";
64
+ case "not_found":
65
+ return "リソースが見つかりませんでした (404)。";
66
+ case "rate_limited":
67
+ return "レート制限に達しました。しばらく待ってから再試行してください。";
68
+ case "server_error":
69
+ return `はてなAPIがサーバーエラーを返しました (${err.status})。`;
70
+ case "bad_request":
71
+ return `リクエストが不正です (${err.status})。`;
72
+ case "parse_error":
73
+ return "AtomPubレスポンスの解析に失敗しました。";
74
+ case "network_error":
75
+ return "はてなAPIに接続できませんでした。";
76
+ default:
77
+ return `はてなAPIでエラーが発生しました (${err.status})。`;
78
+ }
79
+ }
80
+ if (err instanceof Error) return err.message;
81
+ return String(err);
82
+ }
@@ -0,0 +1,38 @@
1
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
2
+ import type { ToolContext } from "./context.js";
3
+ import { registerCategoryTools } from "./tools/categories.js";
4
+ import { registerEntryTools } from "./tools/entries.js";
5
+ import { registerImageTools } from "./tools/images.js";
6
+ import { registerPageTools } from "./tools/pages.js";
7
+
8
+ /**
9
+ * Server metadata reported via the MCP `initialize` handshake.
10
+ *
11
+ * Kept as a constant so the Workers adapter and any future test harnesses
12
+ * see the same name/version without having to repeat string literals.
13
+ */
14
+ export const SERVER_INFO = {
15
+ name: "hatena-blog-mcp",
16
+ version: "0.1.0",
17
+ } as const;
18
+
19
+ /**
20
+ * Build a fresh {@link McpServer} scoped to one request's credentials.
21
+ *
22
+ * We deliberately instantiate a new server per request rather than holding
23
+ * a long-lived singleton: tool handlers close over `ctx.credentials`, and
24
+ * the BYOK model means every request brings its own Authorization header.
25
+ * Re-using a server across requests would leak credentials between callers.
26
+ */
27
+ export function createServer(ctx: ToolContext): McpServer {
28
+ const server = new McpServer(SERVER_INFO, {
29
+ capabilities: {
30
+ tools: {},
31
+ },
32
+ });
33
+ registerEntryTools(server, ctx);
34
+ registerPageTools(server, ctx);
35
+ registerCategoryTools(server, ctx);
36
+ registerImageTools(server, ctx);
37
+ return server;
38
+ }
@@ -0,0 +1,48 @@
1
+ import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
2
+ import { z } from "zod";
3
+ import { MAX_IDENTIFIER_CHARS } from "../../utils/limits.js";
4
+ import { makeClient, type ToolContext } from "../context.js";
5
+ import { ok, type ToolTextResult, toolError } from "../response.js";
6
+
7
+ interface ListCategoriesArgs {
8
+ blog_id: string;
9
+ hatena_id?: string | undefined;
10
+ }
11
+
12
+ export async function listCategoriesHandler(
13
+ args: ListCategoriesArgs,
14
+ ctx: ToolContext,
15
+ ): Promise<ToolTextResult> {
16
+ try {
17
+ const client = makeClient(ctx, args.blog_id, args.hatena_id);
18
+ const doc = await client.listCategories();
19
+ return ok({ categories: doc.categories, fixed: doc.fixed });
20
+ } catch (err) {
21
+ return toolError(err, { operation: "list_categories", requestId: ctx.requestId });
22
+ }
23
+ }
24
+
25
+ export function registerCategoryTools(server: McpServer, ctx: ToolContext): void {
26
+ server.registerTool(
27
+ "list_categories",
28
+ {
29
+ description:
30
+ "ブログのカテゴリ一覧を取得します。fixed=true の場合は新規カテゴリの追加が禁止されています。",
31
+ inputSchema: {
32
+ blog_id: z
33
+ .string()
34
+ .min(1)
35
+ .max(MAX_IDENTIFIER_CHARS)
36
+ .describe("Blog ID, e.g. example.hatenablog.com"),
37
+ hatena_id: z
38
+ .string()
39
+ .min(1)
40
+ .max(MAX_IDENTIFIER_CHARS)
41
+ .optional()
42
+ .describe("Override the Hatena ID derived from the Authorization header"),
43
+ },
44
+ annotations: { readOnlyHint: true },
45
+ },
46
+ (args) => listCategoriesHandler(args, ctx),
47
+ );
48
+ }