daiso-mcp 0.1.0 → 0.1.1

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.
package/CHANGELOG.md ADDED
@@ -0,0 +1,15 @@
1
+ # Changelog
2
+
3
+ ## 0.1.1
4
+
5
+ - 商品検索は、サイトが 0 件と出しているときは空を返す。件数が 0 でないときも、検索語と一致しないカードは捨てる。
6
+ - 照合は NFKC、小文字、ひらがなをカタカナ、ヴァ行をバ行、長音とハイフンの除去、空白と記号の除去の順で揃える。空白とハイフンを除いて 8〜14 桁なら JAN として扱い、サイトへは数字だけを送り、handle か JAN の完全一致だけを残す。
7
+ - すべての語を含む商品があればそれだけを返す。なければ一部の語を含む商品を `partial_match` で返し、要約にもその旨を書く。照合先は商品名と handle。1 件も残らないときは `filtered_out` と「サイトの検索結果は検索語と一致しませんでした」を返す。サイトの件数表示は `result_count_text` のまま、返した件数は `returned_count` に分ける。UCP の `search_catalog` も同じ規則にする。フィルタで空になったページは続きを最大2ページまで読み、まだ続きがあるときはその旨を返す。JAN で UCP 側に JAN も一致する handle も無いときは公開 HTML に戻す。
8
+ - `search_stores` は店名と住所の部分一致である。駅やランドマークは `find_stores_nearby` に緯度経度を渡す。
9
+ - `get_store` の要約は店名、営業時間、住所と、店舗在庫が含まれない旨。
10
+
11
+ ## 0.1.0
12
+
13
+ - ダイソーの通販商品と店舗を、依頼のたびに読む MCP サーバーの初回公開。
14
+ - 通販在庫は `search_products` と `get_product`。店舗在庫は返さず、`explain_store_stock` が公式アプリへの案内だけを返す。
15
+ - UCP は `DAISO_UCP_AGENT_PROFILE` に自分の https プロファイルがあるときだけ使う。
package/README.md CHANGED
@@ -10,7 +10,7 @@
10
10
  |---|---|
11
11
  | `search_products` | 商品名または JAN でネットストアを検索。在庫は**通販在庫** |
12
12
  | `get_product` | 商品詳細(税込価格、説明、JAN、通販在庫) |
13
- | `search_stores` | 地名・店名で店舗検索(企業サイト) |
13
+ | `search_stores` | 店名・住所で店舗検索(企業サイト)。駅やランドマークは `find_stores_nearby` |
14
14
  | `get_store` | 店舗IDの営業時間・住所・サービス |
15
15
  | `find_stores_nearby` | 緯度経度の周辺店舗(公式マップの LocationSmart) |
16
16
  | `list_prefecture_stores` | 都道府県の店舗を1ページだけ取得 |
@@ -187,7 +187,7 @@ JPY 以外の UCP 金額は円として扱いません。
187
187
 
188
188
  ## 店舗
189
189
 
190
- - キーワード検索は `https://www.daiso-sangyo.co.jp/shop/result?keyword=`。空の keyword は全店のページ送りになるため拒否します。
190
+ - キーワード検索は `https://www.daiso-sangyo.co.jp/shop/result?keyword=`。店名と住所の部分一致です。空の keyword は全店のページ送りになるため拒否します。駅名やランドマークの近く(例: 扇町)は、住所にその文字を含む別の店だけが返ることがあります。そのときは `find_stores_nearby` に緯度経度を渡してください。
191
191
  - 詳細は `/shop/detail/{id}`。電話が「-」の店は `phone: null` です。
192
192
  - 都道府県は `/shop/pref/1`(北海道)から `/shop/pref/47`(沖縄県)。`東京` や `13` も受けます。指定した1ページだけを取得します。
193
193
  - 近隣店舗は公式マップと同じ `https://daisosangyo.locationsmart.org/map/g2` です。範囲は半径およそ20km(東西・南北それぞれ約40km)までです。`size` は数値のまま返します(`size=3` が大型店と一致した例はありますが、対応表は未確定です)。Google Maps のキーは読みません。
package/dist/http.js CHANGED
@@ -168,8 +168,9 @@ export function productHtmlNeedsBrowser(html) {
168
168
  return false;
169
169
  if (html.includes("collection__products-count"))
170
170
  return false;
171
- if (/検索結果:\s*0件|0件の内|該当する商品はありません/.test(html))
171
+ if (/検索結果:\s*0件|検索結果0件|0件の内|該当する商品はありません|見つかりませんでした/.test(html)) {
172
172
  return false;
173
+ }
173
174
  return true;
174
175
  }
175
176
  export function storeListNeedsBrowser(html) {
@@ -3,21 +3,29 @@ import { DaisoError } from "../errors.js";
3
3
  import { parseHtmlPrice } from "../prices.js";
4
4
  import { absoluteUrl, clean, imageUrl } from "../text.js";
5
5
  import { NET_STORE_ORIGIN, STOCK_NOTE } from "../version.js";
6
- export function parseProductSearchHtml(html, limit) {
6
+ const FILTERED_MESSAGE = "サイトの検索結果は検索語と一致しませんでした";
7
+ const LONG_VOWEL_OR_HYPHEN = /[\u30fc\uff70\u002d\u2010-\u2015\u2212]/g;
8
+ export function parseProductSearchHtml(html, limit, query) {
7
9
  const $ = load(html);
10
+ const site = readSiteSearchState($);
11
+ if (site.zero) {
12
+ return { products: [], result_count_text: site.result_count_text, returned_count: 0 };
13
+ }
14
+ // Semantic search pads a no-hit page with unrelated cards inside the results grid
15
+ // and a non-zero count. Cards outside `.product-list` are recommendations, not hits.
16
+ const lists = $(".product-list");
17
+ const cards = (lists.length > 0 ? lists.find(".product-item") : $(".product-item")).toArray();
8
18
  const products = [];
9
- $(".product-item").each((_, element) => {
10
- if (products.length >= limit)
11
- return;
19
+ for (const element of cards) {
12
20
  const card = $(element);
13
21
  const href = card.find("a.product-item__title").attr("href") ?? card.find("a").attr("href");
14
22
  if (!href || !href.includes("/products/"))
15
- return;
23
+ continue;
16
24
  const url = absoluteUrl(href, NET_STORE_ORIGIN);
17
25
  const handle = handleFromUrl(url);
18
26
  const title = clean(card.find(".product-item__title").first().text());
19
27
  if (!title)
20
- return;
28
+ continue;
21
29
  const price = parseHtmlPrice(card.find(".product-item__price-list .price").first().text());
22
30
  const label = clean(card.find(".product-item__label-list").text());
23
31
  const onlineAvailable = /在庫なし|売切|sold out/i.test(label) ? false : null;
@@ -41,11 +49,123 @@ export function parseProductSearchHtml(html, limit) {
41
49
  stock_kind: "online",
42
50
  stock_label: "通販在庫",
43
51
  });
44
- });
52
+ }
53
+ const selected = selectRelevantProducts(products, query, limit);
54
+ return { ...selected, result_count_text: site.result_count_text };
55
+ }
56
+ function readSiteSearchState($) {
57
+ const countText = clean($(".collection__products-count").first().text());
45
58
  const showing = clean($(".collection__showing-count").first().text());
46
- const count = clean($(".collection__products-count").first().text());
47
- const resultCount = [count, showing].filter(Boolean).join(" / ") || undefined;
48
- return { products, result_count_text: resultCount };
59
+ const og = clean($('meta[property="og:title"]').attr("content"));
60
+ const description = clean($(".empty-state__description").first().text());
61
+ const listed = [countText, showing].filter(Boolean).join(" / ") || undefined;
62
+ const count = firstDefined(countIn(countText), countIn(showing), countIn(og));
63
+ if (count === 0) {
64
+ return { zero: true, result_count_text: listed ?? (og || "検索結果:0件") };
65
+ }
66
+ if (count !== undefined)
67
+ return { zero: false, result_count_text: listed ?? og };
68
+ const marker = zeroMarker($, description);
69
+ if (marker)
70
+ return { zero: true, result_count_text: marker };
71
+ return { zero: false, result_count_text: listed };
72
+ }
73
+ function firstDefined(...values) {
74
+ return values.find((value) => value !== undefined);
75
+ }
76
+ function countIn(text) {
77
+ if (!text)
78
+ return undefined;
79
+ const labeled = /検索結果\s*[::]?\s*(\d+)\s*件/.exec(text);
80
+ if (labeled?.[1])
81
+ return Number(labeled[1]);
82
+ const showing = /(?:^|\D)(\d+)\s*件の内/.exec(text);
83
+ if (showing?.[1])
84
+ return Number(showing[1]);
85
+ return undefined;
86
+ }
87
+ function zeroMarker($, description) {
88
+ if (/見つかりません|該当する商品はありません/.test(description))
89
+ return description;
90
+ if ($(".empty-state").length === 0)
91
+ return undefined;
92
+ return description || clean($(".empty-state__heading").first().text()) || "検索結果:0件";
93
+ }
94
+ export function selectRelevantProducts(products, query, limit) {
95
+ const capped = products.slice(0, limit);
96
+ if (!query?.trim())
97
+ return { products: capped, returned_count: capped.length };
98
+ const jan = janQuery(query);
99
+ if (jan) {
100
+ const matched = products.filter((product) => product.jan === jan || product.handle === jan);
101
+ return pack(products, matched, limit, false);
102
+ }
103
+ const terms = queryTerms(query);
104
+ if (terms.length === 0)
105
+ return pack(products, [], limit, false);
106
+ const haystacks = products.map((product) => ({
107
+ product,
108
+ fields: [product.title, product.handle]
109
+ .filter((part) => Boolean(part))
110
+ .map((part) => normalizeSearchText(part)),
111
+ }));
112
+ const matches = (entry, term) => entry.fields.some((field) => field.includes(term));
113
+ const all = haystacks.filter((entry) => terms.every((term) => matches(entry, term)));
114
+ if (all.length > 0)
115
+ return pack(products, all.map((entry) => entry.product), limit, false);
116
+ const any = haystacks.filter((entry) => terms.some((term) => matches(entry, term)));
117
+ if (any.length > 0)
118
+ return pack(products, any.map((entry) => entry.product), limit, true);
119
+ return pack(products, [], limit, false);
120
+ }
121
+ function pack(source, matched, limit, partial) {
122
+ if (matched.length === 0) {
123
+ return {
124
+ products: [],
125
+ returned_count: 0,
126
+ filtered_out: source.length,
127
+ message: FILTERED_MESSAGE,
128
+ };
129
+ }
130
+ const products = matched.slice(0, limit);
131
+ return {
132
+ products,
133
+ returned_count: products.length,
134
+ ...(partial ? { partial_match: true } : {}),
135
+ };
136
+ }
137
+ function janQuery(query) {
138
+ const digits = query.normalize("NFKC").replace(LONG_VOWEL_OR_HYPHEN, "").replace(/\s+/g, "");
139
+ return /^\d{8,14}$/.test(digits) ? digits : undefined;
140
+ }
141
+ /** The net store does not find a JAN that still contains spaces or hyphens. */
142
+ export function upstreamSearchQuery(query) {
143
+ return janQuery(query) ?? query;
144
+ }
145
+ function queryTerms(query) {
146
+ const folded = kanaFold(query).replace(LONG_VOWEL_OR_HYPHEN, "");
147
+ return folded
148
+ .split(/[\s\p{P}\p{S}]+/u)
149
+ .map((part) => part.replace(/[\s\p{P}\p{S}]/gu, ""))
150
+ .filter((part) => part.length > 0);
151
+ }
152
+ export function normalizeSearchText(value) {
153
+ return kanaFold(value)
154
+ .replace(LONG_VOWEL_OR_HYPHEN, "")
155
+ .replace(/[\s\p{P}\p{S}]/gu, "");
156
+ }
157
+ function kanaFold(value) {
158
+ let folded = "";
159
+ for (const char of value.normalize("NFKC").toLowerCase()) {
160
+ const code = char.codePointAt(0) ?? 0;
161
+ folded += code >= 0x3041 && code <= 0x3096 ? String.fromCodePoint(code + 0x60) : char;
162
+ }
163
+ return folded
164
+ .replaceAll("ヴァ", "バ")
165
+ .replaceAll("ヴィ", "ビ")
166
+ .replaceAll("ヴェ", "ベ")
167
+ .replaceAll("ヴォ", "ボ")
168
+ .replaceAll("ヴ", "ブ");
49
169
  }
50
170
  export function handleFromUrl(url) {
51
171
  try {
package/dist/server.js CHANGED
@@ -54,9 +54,13 @@ function registerTools(server, app) {
54
54
  }, async (args) => run(() => app.getProduct(args)));
55
55
  server.registerTool("search_stores", {
56
56
  title: "店舗をキーワード検索",
57
- description: "ダイソー企業サイトの店舗検索です。地名や店名を keyword に指定します。空文字は全店クロールになるため拒否します。在庫は含まれません。1回の呼び出しで指定ページだけを取得します。",
57
+ description: "ダイソー企業サイトの店舗検索です。keyword は店名と住所の部分一致です。駅名やランドマーク(扇町のような地名)の近くを探すときは、このツールではなく find_stores_nearby に緯度経度を渡してください。空文字は全店クロールになるため拒否します。在庫は含まれません。1回の呼び出しで指定ページだけを取得します。",
58
58
  inputSchema: {
59
- keyword: z.string().min(1).max(80).describe("地名、店名などのキーワード"),
59
+ keyword: z
60
+ .string()
61
+ .min(1)
62
+ .max(80)
63
+ .describe("店名または住所の一部。駅やランドマークは find_stores_nearby を使います"),
60
64
  page: z
61
65
  .number()
62
66
  .int()
@@ -171,8 +175,13 @@ function summarize(data) {
171
175
  if (products) {
172
176
  const lines = products.slice(0, 10).map((entry) => productLine(entry));
173
177
  const source = typeof data.source === "string" ? data.source : "unknown";
174
- const header = `通販の検索結果(ソース: ${source})${typeof data.fallback_reason === "string" ? `\n${data.fallback_reason}` : ""}`;
175
- return [header, ...lines, "在庫は通販在庫です。店舗在庫ではありません。"]
178
+ const returned = typeof data.returned_count === "number" ? `、返却${data.returned_count}件` : "";
179
+ const header = `通販の検索結果(ソース: ${source}${returned})${typeof data.fallback_reason === "string" ? `\n${data.fallback_reason}` : ""}`;
180
+ const partial = data.partial_match === true
181
+ ? "すべての検索語を含む商品がないため、一部の語に一致した商品を返しました"
182
+ : "";
183
+ const message = typeof data.message === "string" ? data.message : "";
184
+ return [header, partial, message, ...lines, "在庫は通販在庫です。店舗在庫ではありません。"]
176
185
  .filter(Boolean)
177
186
  .join("\n");
178
187
  }
@@ -198,6 +207,12 @@ function summarize(data) {
198
207
  "店舗在庫は含まれません。",
199
208
  ].join("\n");
200
209
  }
210
+ if (typeof data.name === "string" && typeof data.id === "string") {
211
+ const hours = typeof data.hours === "string" ? data.hours : "";
212
+ const address = typeof data.address === "string" ? data.address : "";
213
+ const line = [data.name, hours, address].filter((part) => part !== "").join(" / ");
214
+ return `${line}\n店舗在庫は含まれません。`;
215
+ }
201
216
  return "結果を JSON で返しました。";
202
217
  }
203
218
  function productLine(value) {
@@ -1,7 +1,7 @@
1
1
  import { DaisoError, errorMessage } from "../errors.js";
2
2
  import { HttpClient, productHtmlNeedsBrowser, storeDetailNeedsBrowser, storeListNeedsBrowser, } from "../http.js";
3
3
  import { assertNearbyBounds, parseNearbyPayload, boundsFromPoint, buildNearbyUrl, distanceMeters, zoomForRadius, } from "../parsers/nearby.js";
4
- import { parseProductRef, parseProductSearchHtml } from "../parsers/product-html.js";
4
+ import { parseProductRef, parseProductSearchHtml, selectRelevantProducts, upstreamSearchQuery, } from "../parsers/product-html.js";
5
5
  import { parseShopifyProductPayload } from "../parsers/product-shopify.js";
6
6
  import { parseStoreDetailHtml, parseStoreListHtml } from "../parsers/store-html.js";
7
7
  import { resolvePrefecture } from "../prefectures.js";
@@ -13,6 +13,7 @@ const BUYER_CONTEXT = {
13
13
  currency: "JPY",
14
14
  address_country: "JP",
15
15
  };
16
+ const MAX_EXTRA_UCP_PAGES = 2;
16
17
  const STORE_NOTE = "この一覧に店舗在庫は含まれません。在庫は explain_store_stock を参照してください。";
17
18
  export function createApp(deps) {
18
19
  const http = new HttpClient({
@@ -38,6 +39,55 @@ export function createApp(deps) {
38
39
  explainStoreStock,
39
40
  };
40
41
  }
42
+ async function readFilteredUcpSearch(ucp, upstream, query, limit, cursor) {
43
+ const jan = /^\d{8,14}$/.test(upstream) ? upstream : undefined;
44
+ let pageCursor = cursor;
45
+ let extra = 0;
46
+ let filteredOut = 0;
47
+ let seen = 0;
48
+ let unverifiable = false;
49
+ let selected = selectRelevantProducts([], query, limit);
50
+ let nextCursor;
51
+ let hasNextPage = false;
52
+ while (true) {
53
+ const data = await ucp.call("search_catalog", {
54
+ catalog: {
55
+ query: upstream,
56
+ context: BUYER_CONTEXT,
57
+ pagination: { limit, ...(pageCursor ? { cursor: pageCursor } : {}) },
58
+ },
59
+ });
60
+ const parsed = readUcpProducts(data);
61
+ selected = selectRelevantProducts(parsed.products, query, limit);
62
+ nextCursor = parsed.cursor;
63
+ hasNextPage = parsed.hasNextPage;
64
+ seen += parsed.products.length;
65
+ if (jan) {
66
+ unverifiable =
67
+ unverifiable || parsed.products.some((product) => !product.jan && product.handle !== jan);
68
+ }
69
+ if (selected.products.length > 0) {
70
+ return { selected, cursor: nextCursor, hasNextPage, fallbackJan: false };
71
+ }
72
+ filteredOut += selected.filtered_out ?? 0;
73
+ const more = hasNextPage && nextCursor && nextCursor !== pageCursor && extra < MAX_EXTRA_UCP_PAGES;
74
+ if (!more)
75
+ break;
76
+ pageCursor = nextCursor;
77
+ extra += 1;
78
+ }
79
+ const message = hasNextPage && selected.message
80
+ ? `${selected.message}。続きのページがあります。`
81
+ : selected.message;
82
+ return {
83
+ selected,
84
+ cursor: nextCursor,
85
+ hasNextPage,
86
+ filteredOut,
87
+ message,
88
+ fallbackJan: Boolean(jan) && (unverifiable || seen === 0),
89
+ };
90
+ }
41
91
  async function searchProducts(http, ucp, deps, input) {
42
92
  const query = input.query.trim();
43
93
  if (!query)
@@ -45,29 +95,32 @@ async function searchProducts(http, ucp, deps, input) {
45
95
  if (query.length > 120)
46
96
  throw new DaisoError("検索語は 120 文字以内にしてください。", "input");
47
97
  const limit = clamp(input.limit ?? 10, 1, 24);
98
+ const upstream = upstreamSearchQuery(query);
48
99
  let fallback;
49
100
  if (ucp.enabled) {
50
101
  try {
51
- const data = await ucp.call("search_catalog", {
52
- catalog: {
102
+ const found = await readFilteredUcpSearch(ucp, upstream, query, limit, input.cursor);
103
+ if (found.fallbackJan && !input.cursor) {
104
+ fallback = "公式UCPの結果に一致する JAN が無かったため、公開HTMLへフォールバックしました。";
105
+ }
106
+ else {
107
+ return {
53
108
  query,
54
- context: BUYER_CONTEXT,
55
- pagination: { limit, ...(input.cursor ? { cursor: input.cursor } : {}) },
56
- },
57
- });
58
- const parsed = readUcpProducts(data);
59
- return {
60
- query,
61
- source: "ucp",
62
- stock_kind: "online",
63
- stock_note: STOCK_NOTE,
64
- products: parsed.products.slice(0, limit),
65
- pagination: {
66
- limit,
67
- cursor: parsed.cursor,
68
- has_next_page: parsed.hasNextPage,
69
- },
70
- };
109
+ source: "ucp",
110
+ stock_kind: "online",
111
+ stock_note: STOCK_NOTE,
112
+ products: found.selected.products,
113
+ returned_count: found.selected.returned_count,
114
+ partial_match: found.selected.partial_match,
115
+ filtered_out: found.filteredOut,
116
+ message: found.message,
117
+ pagination: {
118
+ limit,
119
+ cursor: found.cursor,
120
+ has_next_page: found.hasNextPage,
121
+ },
122
+ };
123
+ }
71
124
  }
72
125
  catch (error) {
73
126
  fallback = `公式UCP search_catalog を利用できなかったため、公開HTMLへフォールバックしました: ${errorMessage(error)}`;
@@ -81,10 +134,10 @@ async function searchProducts(http, ucp, deps, input) {
81
134
  throw new DaisoError(`${fallback} 続きページの cursor は UCP でのみ使えます。HTML 検索は robots.txt の *?page=* を避けるため、ページパラメータでは辿りません。`, "ucp");
82
135
  }
83
136
  const url = new URL("/search", NET_STORE_ORIGIN);
84
- url.searchParams.set("q", query);
137
+ url.searchParams.set("q", upstream);
85
138
  url.searchParams.set("type", "product");
86
139
  const html = await readHtml(http, deps, url.href, productHtmlNeedsBrowser);
87
- const parsed = parseProductSearchHtml(html, limit);
140
+ const parsed = parseProductSearchHtml(html, limit, query);
88
141
  return {
89
142
  query,
90
143
  source: "html",
@@ -93,6 +146,10 @@ async function searchProducts(http, ucp, deps, input) {
93
146
  stock_note: STOCK_NOTE,
94
147
  products: parsed.products,
95
148
  result_count_text: parsed.result_count_text,
149
+ returned_count: parsed.returned_count,
150
+ partial_match: parsed.partial_match,
151
+ filtered_out: parsed.filtered_out,
152
+ message: parsed.message,
96
153
  pagination: { limit, has_next_page: false },
97
154
  };
98
155
  }
package/dist/version.js CHANGED
@@ -1,4 +1,4 @@
1
- export const VERSION = "0.1.0";
1
+ export const VERSION = "0.1.1";
2
2
  export const USER_AGENT = `DaisoMCP/${VERSION} (read-only; user-initiated lookup; not a crawler)`;
3
3
  export const NET_STORE_ORIGIN = "https://jp.daisonet.com";
4
4
  export const CORPORATE_ORIGIN = "https://www.daiso-sangyo.co.jp";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "daiso-mcp",
3
- "version": "0.1.0",
3
+ "version": "0.1.1",
4
4
  "description": "非公式。DAISO(ダイソー)の通販商品と店舗を検索する MCP サーバー。大創産業および DAISO とは関係ありません。店舗在庫は返しません。",
5
5
  "keywords": [
6
6
  "mcp",
@@ -22,6 +22,7 @@
22
22
  "files": [
23
23
  "dist",
24
24
  "README.md",
25
+ "CHANGELOG.md",
25
26
  "LICENSE",
26
27
  "NOTICE"
27
28
  ],