lymcp 0.1.0__py3-none-any.whl

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.
lymcp/__init__.py ADDED
File without changes
lymcp/py.typed ADDED
File without changes
lymcp/server.py ADDED
@@ -0,0 +1,354 @@
1
+ import json
2
+ from typing import Annotated
3
+ from typing import Any
4
+
5
+ import httpx
6
+ from loguru import logger
7
+ from mcp.server.fastmcp import FastMCP
8
+ from pydantic import BaseModel
9
+ from pydantic import Field
10
+
11
+ # https://github.com/jlowin/fastmcp/issues/81#issuecomment-2714245145
12
+ mcp = FastMCP("立法院 API v2 MCP Server", log_level="ERROR")
13
+
14
+ BASE_URL = "https://ly.govapi.tw/v2"
15
+
16
+
17
+ # Data models for structured responses
18
+ class BillSummary(BaseModel):
19
+ """議案摘要資訊"""
20
+
21
+ bill_no: str | None = Field(None, description="議案編號")
22
+ title: str | None = Field(None, description="議案標題")
23
+ category: str | None = Field(None, description="議案類別")
24
+ proposer: str | None = Field(None, description="提案人")
25
+ status: str | None = Field(None, description="議案狀態")
26
+ proposal_date: str | None = Field(None, description="提案日期")
27
+
28
+
29
+ class APIResponse(BaseModel):
30
+ """標準化 API 回應格式"""
31
+
32
+ success: bool = Field(description="請求是否成功")
33
+ message: str = Field(description="回應訊息或錯誤說明")
34
+ data: Any | None = Field(None, description="回應資料")
35
+ total: int | None = Field(None, description="總筆數")
36
+ page: int | None = Field(None, description="目前頁數")
37
+ limit: int | None = Field(None, description="每頁筆數")
38
+
39
+
40
+ async def make_api_request(
41
+ endpoint: str, params: dict[str, Any] | None = None, description: str = "API request"
42
+ ) -> APIResponse:
43
+ """統一的 API 請求處理函數,包含完整的錯誤處理和記錄"""
44
+
45
+ url = f"{BASE_URL}{endpoint}"
46
+ logger.info(f"Making {description} request to {url} with params: {params}")
47
+
48
+ async with httpx.AsyncClient(timeout=30.0) as client:
49
+ try:
50
+ response = await client.get(url, params=params)
51
+
52
+ # 記錄回應狀態
53
+ logger.info(f"API response status: {response.status_code}")
54
+
55
+ # 處理各種 HTTP 狀態碼
56
+ if response.status_code == 404:
57
+ return APIResponse(success=False, message="查無資料:所查詢的資源不存在 (404)。請檢查參數是否正確。")
58
+ elif response.status_code == 429:
59
+ return APIResponse(success=False, message="請求過於頻繁 (429)。請稍後再試。")
60
+ elif response.status_code == 500:
61
+ return APIResponse(success=False, message="伺服器內部錯誤 (500)。API 服務可能暫時不可用。")
62
+ elif response.status_code != 200:
63
+ return APIResponse(success=False, message=f"API 請求失敗:HTTP {response.status_code}")
64
+
65
+ # 檢查回應內容
66
+ if not response.text or response.text.strip() == "":
67
+ logger.warning(f"Empty response from {url}")
68
+ return APIResponse(
69
+ success=False,
70
+ message="API 回傳空白內容。可能原因:該資源無資料、API 資料延遲更新、或查詢條件過於嚴格。",
71
+ )
72
+
73
+ # 嘗試解析 JSON
74
+ try:
75
+ data = response.json()
76
+ logger.info(f"Successfully parsed JSON response with {len(str(data))} characters")
77
+
78
+ # 檢查 API 是否回傳錯誤 (有些 API 回傳 200 但內容是錯誤)
79
+ if isinstance(data, dict) and data.get("error") is True:
80
+ error_message = data.get("message", "API 回傳錯誤但未提供詳細訊息")
81
+ return APIResponse(success=False, message=f"API 錯誤:{error_message}")
82
+
83
+ # 提取分頁資訊
84
+ total = data.get("total") if isinstance(data, dict) else None
85
+ page = data.get("page") if isinstance(data, dict) else None
86
+ limit = data.get("limit") if isinstance(data, dict) else None
87
+
88
+ return APIResponse(success=True, data=data, message="查詢成功", total=total, page=page, limit=limit)
89
+ except json.JSONDecodeError as e:
90
+ logger.error(f"Failed to parse JSON response: {e}")
91
+ return APIResponse(
92
+ success=False,
93
+ message=f"API 回傳資料格式異常:無法解析 JSON 格式。原始內容長度:{len(response.text)} 字元",
94
+ )
95
+
96
+ except httpx.TimeoutException:
97
+ logger.error(f"Timeout for request to {url}")
98
+ return APIResponse(success=False, message="請求逾時。API 服務可能繁忙,請稍後再試。")
99
+ except httpx.ConnectError:
100
+ logger.error(f"Connection error for request to {url}")
101
+ return APIResponse(success=False, message="連線錯誤。請檢查網路連線或 API 服務是否正常。")
102
+ except Exception as e:
103
+ logger.error(f"Unexpected error for request to {url}: {e}")
104
+ return APIResponse(success=False, message=f"未預期的錯誤:{str(e)}")
105
+
106
+
107
+ def extract_bill_summary(bill_data: dict[str, Any]) -> BillSummary:
108
+ """從 API 資料中提取議案摘要資訊"""
109
+ # 處理提案人可能是 list 的情況
110
+ proposer = bill_data.get("提案人")
111
+ if isinstance(proposer, list):
112
+ proposer = ", ".join(proposer) if proposer else None
113
+
114
+ return BillSummary(
115
+ bill_no=bill_data.get("議案編號"),
116
+ title=bill_data.get("議案名稱") or bill_data.get("案由"),
117
+ category=bill_data.get("議案類別"),
118
+ proposer=proposer,
119
+ status=bill_data.get("議案狀態"),
120
+ proposal_date=bill_data.get("提案日期"),
121
+ )
122
+
123
+
124
+ @mcp.tool()
125
+ async def search_bills(
126
+ term: Annotated[int | None, Field(description="議案所屬屆期,例: 11")] = None,
127
+ session: Annotated[int | None, Field(description="議案所屬會期,例: 2")] = None,
128
+ bill_category: Annotated[str | None, Field(description="議案類別,例: 法律案")] = None,
129
+ proposer: Annotated[str | None, Field(description="提案人,例: 徐欣瑩")] = None,
130
+ cosigner: Annotated[str | None, Field(description="連署人,例: 林德福")] = None,
131
+ bill_status: Annotated[str | None, Field(description="議案目前所處狀態,例: 交付審查")] = None,
132
+ proposal_source: Annotated[str | None, Field(description="議案的提案來源屬性,例: 委員提案")] = None,
133
+ bill_no: Annotated[str | None, Field(description="議案編號,例: 202110068550000")] = None,
134
+ page: Annotated[int, Field(description="頁數")] = 1,
135
+ limit: Annotated[int, Field(description="每頁筆數")] = 20,
136
+ structured: Annotated[bool, Field(description="是否回傳結構化摘要資訊")] = False,
137
+ ) -> str:
138
+ """
139
+ 搜尋立法院議案列表。可依據屆期、會期、議案類別、提案人等條件進行篩選。
140
+
141
+ 參數說明:
142
+ - term: 屆期,如第11屆
143
+ - session: 會期,如第2會期
144
+ - bill_category: 議案類別,如「法律案」、「預算案」
145
+ - proposer: 提案人姓名
146
+ - cosigner: 連署人姓名
147
+ - bill_status: 議案狀態,如「交付審查」、「一讀」
148
+ - proposal_source: 提案來源,如「委員提案」、「政府提案」
149
+ - bill_no: 特定議案編號
150
+ - page: 頁數 (預設1)
151
+ - limit: 每頁筆數 (預設20,建議不超過100)
152
+ - structured: 是否回傳結構化摘要 (預設False,回傳完整JSON)
153
+
154
+ 回傳格式:
155
+ - structured=False: 完整 JSON 資料
156
+ - structured=True: 結構化摘要,包含議案編號、標題、類別、提案人、狀態等主要資訊
157
+ """
158
+
159
+ params: dict[str, Any] = {"page": page, "limit": limit}
160
+
161
+ if term is not None:
162
+ params["屆"] = term
163
+ if session is not None:
164
+ params["會期"] = session
165
+ if bill_category:
166
+ params["議案類別"] = bill_category
167
+ if proposer:
168
+ params["提案人"] = proposer
169
+ if cosigner:
170
+ params["連署人"] = cosigner
171
+ if bill_status:
172
+ params["議案狀態"] = bill_status
173
+ if proposal_source:
174
+ params["提案來源"] = proposal_source
175
+ if bill_no:
176
+ params["議案編號"] = bill_no
177
+
178
+ # 使用統一的 API 請求處理
179
+ api_response = await make_api_request("/bills", params, "搜尋議案列表")
180
+
181
+ if not api_response.success:
182
+ return f"❌ {api_response.message}"
183
+
184
+ if structured and api_response.data:
185
+ try:
186
+ # 提取結構化摘要
187
+ bills_data = api_response.data
188
+ if isinstance(bills_data, dict) and "bills" in bills_data:
189
+ bills = bills_data["bills"]
190
+ summaries = [extract_bill_summary(bill) for bill in bills]
191
+
192
+ result = {
193
+ "查詢結果摘要": {
194
+ "總筆數": api_response.total,
195
+ "目前頁數": api_response.page,
196
+ "每頁筆數": api_response.limit,
197
+ "本頁筆數": len(summaries),
198
+ },
199
+ "議案列表": [summary.model_dump() for summary in summaries],
200
+ }
201
+ return f"✅ {api_response.message}\n\n{json.dumps(result, ensure_ascii=False, indent=2)}"
202
+ else:
203
+ return "⚠️ 資料格式異常:無法提取議案列表"
204
+ except Exception as e:
205
+ logger.error(f"Failed to structure bills data: {e}")
206
+ return f"⚠️ 結構化處理失敗:{str(e)}\n\n原始資料:{json.dumps(api_response.data, ensure_ascii=False)}"
207
+
208
+ # 回傳完整 JSON
209
+ return f"✅ {api_response.message}\n\n{json.dumps(api_response.data, ensure_ascii=False, indent=2)}"
210
+
211
+
212
+ @mcp.tool()
213
+ async def get_bill_detail(
214
+ bill_no: Annotated[str, Field(description="議案編號,例: 203110077970000")],
215
+ structured: Annotated[bool, Field(description="是否回傳結構化摘要資訊")] = False,
216
+ ) -> str:
217
+ """
218
+ 取得特定議案的詳細資訊。
219
+
220
+ 參數說明:
221
+ - bill_no: 議案編號,必填 (例: 203110077970000)
222
+ - structured: 是否回傳結構化摘要 (預設False,回傳完整JSON)
223
+
224
+ 回傳內容包含議案基本資料、提案人資訊、議案流程、相關法條等詳細資訊。
225
+ """
226
+
227
+ api_response = await make_api_request(f"/bills/{bill_no}", None, f"取得議案 {bill_no} 詳細資訊")
228
+
229
+ if not api_response.success:
230
+ return f"❌ {api_response.message}"
231
+
232
+ if structured and api_response.data:
233
+ try:
234
+ bill_data = api_response.data
235
+ summary = extract_bill_summary(bill_data)
236
+
237
+ # 提取更多詳細資訊
238
+ detail_info = {
239
+ "基本資訊": summary.model_dump(),
240
+ "議案流程": bill_data.get("議案流程", []),
241
+ "提案說明": bill_data.get("提案說明") or bill_data.get("案由"),
242
+ "相關法條": bill_data.get("相關法條", []),
243
+ "委員會": bill_data.get("委員會"),
244
+ "文件": bill_data.get("文件", []),
245
+ }
246
+
247
+ return f"✅ {api_response.message}\n\n{json.dumps(detail_info, ensure_ascii=False, indent=2)}"
248
+ except Exception as e:
249
+ logger.error(f"Failed to structure bill detail: {e}")
250
+ return f"⚠️ 結構化處理失敗:{str(e)}\n\n原始資料:{json.dumps(api_response.data, ensure_ascii=False)}"
251
+
252
+ return f"✅ {api_response.message}\n\n{json.dumps(api_response.data, ensure_ascii=False, indent=2)}"
253
+
254
+
255
+ @mcp.tool()
256
+ async def get_bill_related_bills(bill_no: Annotated[str, Field(description="議案編號,例: 203110077970000")]) -> str:
257
+ """
258
+ 取得特定議案的相關議案列表。
259
+
260
+ 參數說明:
261
+ - bill_no: 議案編號,必填 (例: 203110077970000)
262
+
263
+ 回傳該議案的相關議案資訊,包含關聯類型、相關議案編號等。
264
+ """
265
+
266
+ api_response = await make_api_request(f"/bills/{bill_no}/related_bills", None, f"取得議案 {bill_no} 相關議案")
267
+
268
+ if not api_response.success:
269
+ return f"❌ {api_response.message}"
270
+
271
+ return f"✅ {api_response.message}\n\n{json.dumps(api_response.data, ensure_ascii=False, indent=2)}"
272
+
273
+
274
+ @mcp.tool()
275
+ async def get_bill_doc_html(bill_no: Annotated[str, Field(description="議案編號,例: 203110077970000")]) -> str:
276
+ """
277
+ 取得特定議案的文件 HTML 內容列表。
278
+
279
+ 參數說明:
280
+ - bill_no: 議案編號,必填 (例: 203110077970000)
281
+
282
+ 回傳該議案的所有相關文件 HTML 內容,包含議案本文、附件、修正對照表等。
283
+
284
+ 注意事項:
285
+ - 若回傳空白內容,可能原因包含:該議案尚無正式文件、文件尚未數位化、或 API 資料延遲更新
286
+ - 建議先使用 get_bill_detail 確認議案存在後再查詢文件內容
287
+ """
288
+
289
+ api_response = await make_api_request(f"/bills/{bill_no}/doc_html", None, f"取得議案 {bill_no} 文件內容")
290
+
291
+ if not api_response.success:
292
+ return f"❌ {api_response.message}"
293
+
294
+ # 特別處理文件內容的空白檢查
295
+ if api_response.data is None or (isinstance(api_response.data, str) and not api_response.data.strip()):
296
+ return (
297
+ "⚠️ 該議案暫無文件 HTML 內容。\n\n"
298
+ "可能原因:\n"
299
+ "1. 該議案尚未產生正式文件\n"
300
+ "2. 文件尚未完成數位化\n"
301
+ "3. API 資料庫更新延遲\n"
302
+ "4. 議案處於早期階段,僅有提案資訊\n\n"
303
+ "建議:請稍後再試,或使用 get_bill_detail 取得議案基本資訊。"
304
+ )
305
+
306
+ return f"✅ {api_response.message}\n\n{json.dumps(api_response.data, ensure_ascii=False, indent=2)}"
307
+
308
+
309
+ @mcp.tool()
310
+ async def get_bill_meets(
311
+ bill_no: Annotated[str, Field(description="議案編號,例: 203110077970000")],
312
+ term: Annotated[int | None, Field(description="屆,例: 11")] = None,
313
+ session: Annotated[int | None, Field(description="會期,例: 2")] = None,
314
+ meeting_type: Annotated[str | None, Field(description="會議種類,例: 院會")] = None,
315
+ date: Annotated[str | None, Field(description="日期,例: 2024-10-25")] = None,
316
+ page: Annotated[int, Field(description="頁數")] = 1,
317
+ limit: Annotated[int, Field(description="每頁筆數")] = 20,
318
+ ) -> str:
319
+ """
320
+ 取得特定議案的相關會議列表。
321
+
322
+ 參數說明:
323
+ - bill_no: 議案編號,必填 (例: 203110077970000)
324
+ - term: 屆期篩選 (例: 11)
325
+ - session: 會期篩選 (例: 2)
326
+ - meeting_type: 會議種類篩選 (例: 院會、委員會)
327
+ - date: 會議日期篩選 (格式: YYYY-MM-DD)
328
+ - page: 頁數 (預設1)
329
+ - limit: 每頁筆數 (預設20)
330
+
331
+ 回傳該議案在各個會議中的審議紀錄,包含會議資訊、審議結果、發言紀錄等。
332
+ """
333
+
334
+ params: dict[str, Any] = {"page": page, "limit": limit}
335
+
336
+ if term is not None:
337
+ params["屆"] = term
338
+ if session is not None:
339
+ params["會期"] = session
340
+ if meeting_type:
341
+ params["會議種類"] = meeting_type
342
+ if date:
343
+ params["日期"] = date
344
+
345
+ api_response = await make_api_request(f"/bills/{bill_no}/meets", params, f"取得議案 {bill_no} 相關會議")
346
+
347
+ if not api_response.success:
348
+ return f"❌ {api_response.message}"
349
+
350
+ return f"✅ {api_response.message}\n\n{json.dumps(api_response.data, ensure_ascii=False, indent=2)}"
351
+
352
+
353
+ def main():
354
+ mcp.run()
@@ -0,0 +1,78 @@
1
+ Metadata-Version: 2.4
2
+ Name: lymcp
3
+ Version: 0.1.0
4
+ Author-email: narumi <toucans-cutouts0f@icloud.com>
5
+ License-File: LICENSE
6
+ Requires-Python: >=3.12
7
+ Requires-Dist: httpx>=0.28.1
8
+ Requires-Dist: loguru>=0.7.3
9
+ Requires-Dist: mcp[cli]>=1.6.0
10
+ Description-Content-Type: text/markdown
11
+
12
+ # ly-mcp
13
+
14
+ A Model Context Protocol (MCP) server for Taiwan's Legislative Yuan API v2, providing bill search, detailed information, related documents, and meeting records.
15
+
16
+ ## Features
17
+
18
+ This MCP server provides the following tools:
19
+
20
+ - **search_bills**: Search bills by term, session, category, proposer, and other criteria
21
+ - **get_bill_detail**: Get comprehensive information about specific bills
22
+ - **get_bill_related_bills**: Query related bills and their associations
23
+ - **get_bill_doc_html**: Retrieve HTML-formatted bill documents
24
+ - **get_bill_meets**: Access bill deliberation records from various meetings
25
+
26
+ ## API Source
27
+
28
+ This MCP server uses the [Legislative Yuan API v2](https://ly.govapi.tw/v2) as its data source, providing information about Taiwan's Legislative Yuan bills and proceedings.
29
+
30
+ ## Installation & Usage
31
+
32
+ ### GitHub
33
+
34
+ ```json
35
+ {
36
+ "mcpServers": {
37
+ "lymcp": {
38
+ "command": "uvx",
39
+ "args": [
40
+ "--from",
41
+ "git+https://github.com/narumiruna/ly-mcp",
42
+ "lymcp"
43
+ ]
44
+ }
45
+ }
46
+ }
47
+ ```
48
+
49
+ ### PyPI
50
+
51
+ ```json
52
+ {
53
+ "mcpServers": {
54
+ "lymcp": {
55
+ "command": "uvx",
56
+ "args": ["lymcp@latest"]
57
+ }
58
+ }
59
+ }
60
+ ```
61
+
62
+ ### Local
63
+
64
+ ```json
65
+ {
66
+ "mcpServers": {
67
+ "lymcp": {
68
+ "command": "uv",
69
+ "args": [
70
+ "run",
71
+ "--directory",
72
+ "/home/<user>/workspace/ly-mcp",
73
+ "lymcp"
74
+ ]
75
+ }
76
+ }
77
+ }
78
+ ```
@@ -0,0 +1,8 @@
1
+ lymcp/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
2
+ lymcp/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
3
+ lymcp/server.py,sha256=DZF3x9eE62DXQ8Piw-cty0OuqYzwmybhXuptbR5xuFs,15328
4
+ lymcp-0.1.0.dist-info/METADATA,sha256=3bF6yUbuHZqKLZVVe5BeaoEJ_QORhyX9zH4q_kuuu9M,1645
5
+ lymcp-0.1.0.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
6
+ lymcp-0.1.0.dist-info/entry_points.txt,sha256=58X3ED9UXZoBTWmAxLIOUDll2tmRYidUux4Ip1OM89U,44
7
+ lymcp-0.1.0.dist-info/licenses/LICENSE,sha256=H2T3_RTgmcngMeC7p_SXT3GwBLkd2DaNgAZuxulcfiA,1066
8
+ lymcp-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.27.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ lymcp = lymcp.server:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2022 なるみ
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.