budhosp-plan 1.0.0

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 KlongchuDev
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.
package/README.md ADDED
@@ -0,0 +1,65 @@
1
+ # budhosp-plan
2
+
3
+ CLI + agent skill สำหรับเชื่อมต่อ **BUDHOSP Plan** ผ่าน MCP (`/mcp/projects`) หรือ REST API v1
4
+ โดยบังคับสองเงื่อนไข: ต้องมี Sanctum API token และต้องระบุ project id หรือ code
5
+
6
+ ใช้ได้กับ Node.js 18+ ไม่มี dependency ภายนอก
7
+
8
+ ## ใช้งานผ่าน npx
9
+
10
+ ```bash
11
+ BUDHOSP_BASE_URL=https://plan.example.go.th \
12
+ BUDHOSP_API_TOKEN=1\|abc... \
13
+ BUDHOSP_PROJECT=HIS-2026 \
14
+ npx budhosp-plan check
15
+ ```
16
+
17
+ หรือติดตั้งในโปรเจกต์:
18
+
19
+ ```bash
20
+ npm install --save-dev budhosp-plan
21
+ npx budhosp-plan projects "HIS"
22
+ ```
23
+
24
+ ## Environment
25
+
26
+ | ตัวแปร | จำเป็น | ความหมาย |
27
+ |---|---|---|
28
+ | `BUDHOSP_BASE_URL` | ใช่ | โดเมนของระบบ เช่น `https://plan.example.go.th` |
29
+ | `BUDHOSP_API_TOKEN` | ใช่ | Sanctum bearer token (fallback: `BUDHOSP_TOKEN`, `BUDHOSP_MCP_TOKEN`) |
30
+ | `BUDHOSP_PROJECT` | แนะนำ | project id หรือ code (ถ้า code เป็นตัวเลขล้วนใช้ `code:<code>`) |
31
+
32
+ ## คำสั่ง
33
+
34
+ ```bash
35
+ budhosp-plan check # ตรวจ REST + MCP + โครงการเริ่มต้น
36
+ budhosp-plan projects [search] # โครงการที่เข้าถึงได้
37
+ budhosp-plan project [id|code] # ยืนยันโครงการ + phases/members
38
+ budhosp-plan tasks [id|code] [status] # รายการงาน
39
+ budhosp-plan tools # ชื่อ MCP tools
40
+ budhosp-plan call <tool> [json] # เรียก MCP tool (เติม project ให้ถ้าตั้งค่าไว้)
41
+ ```
42
+
43
+ ตัวอย่าง:
44
+
45
+ ```bash
46
+ budhosp-plan call get_project '{"project":"HIS-2026"}'
47
+ budhosp-plan call create_task '{"project":"HIS-2026","title":"Kickoff","start_date":"2026-11-20","due_date":"2026-11-27"}'
48
+ ```
49
+
50
+ ## ใช้เป็น agent skill
51
+
52
+ แพ็กเกจนี้มี `SKILL.md` และ `references/` อยู่ด้วย agent ที่รองรับ skill directory
53
+ สามารถชี้ไปที่ `node_modules/budhosp-plan/SKILL.md` หรือคัดลอกโฟลเดอร์ไปที่
54
+ `.agents/skills/budhosp-plan/`, `.kilo/skills/budhosp-plan/` หรือ `.claude/skills/budhosp-plan/`
55
+
56
+ ## ความปลอดภัย
57
+
58
+ - token อ่านจาก environment เท่านั้น ไม่ถูกเขียนลงไฟล์หรือ log
59
+ - ห้าม commit token; ถ้า token หลุดให้ rotate/เพิกถอนทันที
60
+ - ใช้บัญชีบริการที่มีสิทธิ์เฉพาะโครงการที่จำเป็น
61
+ - `check` เป็นการอ่าน ไม่ได้พิสูจน์สิทธิ์เขียน
62
+
63
+ ## License
64
+
65
+ MIT
package/SKILL.md ADDED
@@ -0,0 +1,244 @@
1
+ ---
2
+ name: budhosp-plan
3
+ description: "เชื่อมต่อและใช้งาน BUDHOSP Plan ผ่าน MCP หรือ REST API เมื่อต้องอ่าน/อัปเดตโครงการ งาน phase กำหนดการ ความคืบหน้า หรือคอมเมนต์ ต้องยืนยันตัวตนด้วย Sanctum API token (BUDHOSP_API_TOKEN) และระบุ project id หรือ project code ก่อนเรียก tool ทุกครั้ง"
4
+ license: MIT
5
+ metadata:
6
+ author: budhosp
7
+ version: "1.0.0"
8
+ ---
9
+
10
+ # BUDHOSP Plan Skill
11
+
12
+ สกิลนี้สำหรับเอเจนต์ในโปรเจกต์อื่นที่ต้องอ่านหรือแก้ไขข้อมูลในระบบ **BUDHOSP Plan**
13
+ ผ่าน MCP endpoint `/mcp/projects` หรือ REST API `/api/v1`
14
+
15
+ **เงื่อนไขบังคับสองข้อ:** ต้องมี Bearer token ที่ผ่านการยืนยันตัวตน และต้องระบุโครงการ
16
+ (project id หรือ project code) ให้ชัดเจนก่อนเรียก tool ทุกครั้ง
17
+
18
+ ## 1. ติดตั้งก่อนใช้งาน
19
+
20
+ ติดตั้งได้สองแบบ:
21
+
22
+ ```bash
23
+ # แบบที่ 1: ใช้เป็น CLI จาก npm (แพ็กเกจมี SKILL.md และ references อยู่ด้วย)
24
+ npm install --save-dev budhosp-plan
25
+ npx budhosp-plan check
26
+
27
+ # แบบที่ 2: คัดลอกโฟลเดอร์ไปยัง skills directory ของ client
28
+ # .agents/skills/budhosp-plan, .kilo/skills/budhosp-plan หรือ .claude/skills/budhosp-plan
29
+ ```
30
+
31
+ แล้วตั้งค่า 3 ค่าต่อไปนี้ใน environment ของ agent หรือไฟล์ `.env` ของโปรเจกต์:
32
+
33
+ | ตัวแปร | จำเป็น | ตัวอย่าง | คำอธิบาย |
34
+ |---|---|---|---|
35
+ | `BUDHOSP_BASE_URL` | ใช่ | `https://project.example.go.th` | URL ของระบบ ไม่ต้องมี `/` ปิดท้าย |
36
+ | `BUDHOSP_API_TOKEN` | ใช่ | `1\|abc...` | Sanctum token ของผู้ใช้/บัญชีบริการ |
37
+ | `BUDHOSP_PROJECT` | แนะนำ | `HIS-2026` หรือ `12` | โครงการเริ่มต้น (project code หรือ id) |
38
+
39
+ สคริปต์ยังรับ `BUDHOSP_TOKEN` หรือ `BUDHOSP_MCP_TOKEN` เป็น fallback
40
+ แต่เอกสารและ config ตัวอย่างใช้ `BUDHOSP_API_TOKEN` เป็นชื่อหลัก
41
+
42
+ ค่า `BUDHOSP_PROJECT` และ argument ของสคริปต์: ถ้าเป็นตัวเลขล้วนจะถือเป็น project id
43
+ ถ้า project code เป็นตัวเลขล้วน ให้ใส่ `code:` นำหน้า เช่น `code:12345`
44
+
45
+ ข้อห้ามเรื่อง token:
46
+
47
+ - ห้าม hardcode token ลงในไฟล์ที่ commit, เอกสาร, log หรือข้อความแชท
48
+ - เก็บใน secret manager หรือ environment variable ของ MCP client
49
+ - token สืบทอดสิทธิ์ของบัญชีเจ้าของ จึงควรใช้บัญชีบริการที่มีสิทธิ์เฉพาะโครงการที่จำเป็น
50
+ - ถ้า token หลุด (ในแชท, log, ไฟล์) ให้ถือว่ารั่วและแจ้งผู้ดูแลเพื่อ rotate/เพิกถอนทันที
51
+
52
+ ### 1.1 ขอ token
53
+
54
+ 1. เข้าสู่ระบบ BUDHOSP Plan ด้วยบัญชีที่จะใช้
55
+ 2. ไปที่ **Profile → API MCP Tokens** แล้วสร้าง token ใหม่ (กำหนดวันหมดอายุได้)
56
+ 3. คัดลอก token ทันที เพราะระบบแสดงเพียงครั้งเดียว
57
+ 4. หรือใช้ `POST /api/v1/auth/login` ด้วย email/password/device_name เพื่อออก token ชั่วคราว
58
+
59
+ ถ้า token หมดอายุหรือถูกเพิกถอน คำขอจะได้ HTTP 401 — ต้องขอ token ใหม่จากผู้ดูแล ไม่ใช่เดาหรือใช้ token เก่า
60
+
61
+ ### 1.2 ตรวจสอบการเชื่อมต่อ
62
+
63
+ ใช้สคริปต์ที่แนบมา (ต้องมี Node.js 18+):
64
+
65
+ ```bash
66
+ node .agents/skills/budhosp-plan/scripts/budhosp.mjs check
67
+ ```
68
+
69
+ หรือตรวจด้วย REST API โดยตรง:
70
+
71
+ ```bash
72
+ curl -s "$BUDHOSP_BASE_URL/api/v1/auth/me" \
73
+ -H "Authorization: Bearer $BUDHOSP_API_TOKEN" \
74
+ -H "Accept: application/json"
75
+ ```
76
+
77
+ ต้องเห็นข้อมูลผู้ใช้ปัจจุบัน การอ่านสำเร็จไม่ได้แปลว่ามีสิทธิ์เขียน
78
+ ให้ตรวจสิทธิ์โครงการด้วย `get_project` ก่อนเสมอ
79
+
80
+ ## 2. การยืนยันตัวตน (Authentication)
81
+
82
+ ทั้ง MCP และ REST API ใช้ Sanctum Bearer token ชุดเดียวกัน:
83
+
84
+ ```
85
+ Authorization: Bearer <BUDHOSP_API_TOKEN>
86
+ ```
87
+
88
+ | รายการ | ค่า |
89
+ |---|---|
90
+ | MCP endpoint | `{BUDHOSP_BASE_URL}/mcp/projects` |
91
+ | MCP transport | Streamable HTTP (Laravel MCP) |
92
+ | Accept header (MCP) | `application/json, text/event-stream` |
93
+ | REST base | `{BUDHOSP_BASE_URL}/api/v1` |
94
+ | Rate limit | 60 requests/นาที ต่อผู้ใช้ (MCP) |
95
+
96
+ ห้ามส่ง token ผ่าน query string หรือ cookie และห้าม log ค่า header แบบเต็ม
97
+
98
+ ## 3. ผูกโครงการ (Project binding) — บังคับ
99
+
100
+ ทุก tool ที่ทำงานกับโครงการต้องมี `project` เป็น **project id หรือ project code**
101
+ ห้ามเดา ห้ามใช้ชื่อโครงการที่คล้ายกัน และห้ามใช้โครงการแรกจากรายการโดยไม่ยืนยัน
102
+
103
+ ลำดับที่ต้องทำ:
104
+
105
+ 1. ถ้าผู้ใช้ยังไม่ระบุโครงการ ให้ถามก่อน
106
+ 2. ถ้าไม่รู้ id/code ให้เรียก `list_projects` (ค้นด้วย `search` ได้) แล้วรายงานตัวเลือกให้ผู้ใช้
107
+ 3. เรียก `get_project` ด้วย id/code ที่เลือก เพื่อยืนยันว่ามีสิทธิ์ และเก็บ:
108
+ - `project.id`, `project.code`, `project.name`
109
+ - `phases[].id`
110
+ - `members[].id` (ใช้เป็น `assignee_ids`)
111
+ 4. ใช้ id/code เดิมนี้กับทุก tool ในงานเดียวกัน และส่ง `project` ทุกครั้งที่ tool รองรับ
112
+ 5. งานที่ได้จาก `list_tasks` ต้องมาจากโครงการเดียวกันกับ `project` ที่ผูกไว้
113
+
114
+ ถ้าผู้ใช้ระบุชื่อโครงการที่ไม่ตรงกับ code ให้ค้นและยืนยันก่อน ห้ามเลือกเองเมื่อพบหลายรายการ
115
+
116
+ ## 4. Tools ที่ใช้ได้
117
+
118
+ | Tool | ทำอะไร | สิทธิ์ขั้นต่ำ |
119
+ |---|---|---|
120
+ | `list_projects` | รายการโครงการที่เข้าถึงได้ | สมาชิกโครงการ (admin เห็นทั้งหมด) |
121
+ | `get_project` | รายละเอียดโครงการ phases members task counts | viewer |
122
+ | `list_tasks` | รายการงานในโครงการ (กรองได้) | viewer |
123
+ | `create_phase` | สร้าง phase ต่อท้ายรายการ | manager / admin |
124
+ | `create_task` | สร้างงานในโครงการ | manager / member |
125
+ | `update_task_status` | เปลี่ยนสถานะ Kanban | manager / member |
126
+ | `update_task_schedule` | เลื่อนวันเริ่ม/ครบกำหนด (auto-shift dependent tasks) | manager / member |
127
+ | `update_task_progress` | ตั้งเปอร์เซ็นต์ความคืบหน้า | manager / member |
128
+ | `add_task_comment` | เพิ่มคอมเมนต์ในงาน | manager / member |
129
+
130
+ รายละเอียดพารามิเตอร์และผลลัพธ์: [references/tools.md](references/tools.md)
131
+
132
+ MCP **ไม่มี** delete, แก้ชื่อ/รายละเอียดงาน, จัดการสมาชิก, dependencies, subtasks, attachments
133
+ หรือออก token — งานเหล่านี้ใช้ REST API หรือหน้าเว็บตามสิทธิ์ของบัญชี
134
+
135
+ ## 5. Workflow
136
+
137
+ ### 5.1 สำรวจโครงการและงาน (read-only)
138
+
139
+ 1. `list_projects` (ใส่ `search` ถ้ารู้ชื่อ/code)
140
+ 2. `get_project` กับโครงการที่เลือก
141
+ 3. `list_tasks` ด้วย `project` เดียวกัน (กรอง `status`, `priority`, `phase_id`)
142
+
143
+ ### 5.2 สร้างงาน
144
+
145
+ 1. ตรวจ `list_tasks` ว่ายังไม่มีงานเดิม (ระวัง limit ที่อาจตัดรายการ)
146
+ 2. ตรวจ `phase_id` ว่าอยู่ใน `phases` ของโครงการนี้ และ `assignee_ids` มาจาก `members`
147
+ 3. ส่ง `create_task` พร้อม `project`, `title`, `start_date`, `due_date` (`YYYY-MM-DD`, due >= start)
148
+ 4. เก็บ `task.id` ที่ได้กลับไปยังระบบต้นทาง เพราะการสร้างไม่มี idempotency key
149
+
150
+ ถ้า timeout ระหว่างสร้าง ห้าม retry ทันที ให้ตรวจ `list_tasks` ว่าสร้างไปแล้วหรือยัง
151
+
152
+ ### 5.3 อัปเดตความคืบหน้า
153
+
154
+ 1. หา `task_id` จาก `list_tasks` หรือ mapping ของระบบต้นทาง และยืนยันว่าเป็นงานที่ถูกต้อง
155
+ 2. เรียก `update_task_progress` (0–100)
156
+ 3. อ่าน `task.progress` และ `task.status` จากผลลัพธ์จริงแล้วรายงาน
157
+ 4. ถ้าต้องส่งต่อ ให้เพิ่ม `add_task_comment` เมื่อได้รับอนุญาต
158
+
159
+ ### 5.4 เลื่อนกำหนดงาน
160
+
161
+ 1. อ่านกำหนดเดิมก่อน
162
+ 2. เรียก `update_task_schedule` พร้อม `start_date` และ `due_date` ใหม่ทั้งคู่
163
+ 3. รายงาน `task` และ `shifted_tasks[]` (งานที่ถูกเลื่อนตาม dependency) ให้ผู้ใช้ทราบ
164
+
165
+ ## 6. กฎการเขียนข้อมูล
166
+
167
+ - อ่านก่อนเขียนทุกครั้ง และใช้ id จากผลลัพธ์จริงเท่านั้น
168
+ - `create_task`, `create_phase`, `add_task_comment` ไม่ idempotent — ตรวจก่อน retry
169
+ - `status`: `todo` | `in_progress` | `in_review` | `done`
170
+ - เปลี่ยนเป็น `done` จะตั้ง progress = 100
171
+ - เปลี่ยน `todo` ขณะ progress = 100 จะรีเซ็ตเป็น 0
172
+ - `priority`: `low` | `medium` | `high` | `urgent`
173
+ - `progress`: 0–100; 100 → `done`, 1–99 → งาน `todo` กลายเป็น `in_progress`
174
+ - วันที่ใช้ `YYYY-MM-DD` เท่านั้น (ไม่ใส่เวลา/timezone)
175
+ - limit ของ `list_projects` = 20 (สูงสุด 100), `list_tasks` = 50 (สูงสุด 200)
176
+ และไม่มี pagination — จำนวนที่คืนไม่ใช่จำนวนทั้งหมดของโครงการ
177
+ - อย่าสร้างงานใหม่เพียงเพราะไม่พบใน `list_tasks` ที่อาจถูก limit ตัด
178
+
179
+ ## 7. การจัดการข้อผิดพลาด
180
+
181
+ | อาการ | การดำเนินการ |
182
+ |---|---|
183
+ | HTTP 401 | token หาย/หมดอายุ/ถูกเพิกถอน — ขอ token ใหม่ ห้ามเดา |
184
+ | authorization error / 403 | บัญชีไม่มีสิทธิ์ในโครงการ — หยุดเขียน แจ้งโครงการและบทบาทที่ต้องใช้ |
185
+ | ไม่พบโครงการ/งาน (404) | อ่านรายการใหม่และยืนยัน mapping ห้ามเดา id |
186
+ | validation error (422) | แก้ field ตามรายละเอียด เช่น วันที่, phase ต่างโครงการ, assignee ไม่ใช่สมาชิก |
187
+ | HTTP 429 | รอและลดความถี่ เคารพ `Retry-After` ถ้ามี |
188
+ | timeout ระหว่างเขียน | ผลลัพธ์ไม่ทราบแน่ชัด — ตรวจข้อมูลจริงก่อนส่งซ้ำ |
189
+ | ไม่พบ tool | เรียก `tools/list` และตรวจเวอร์ชัน ห้ามเดาชื่อ tool |
190
+
191
+ ข้อความ error จากระบบอาจเป็นภาษาไทย ให้รายงานต่อผู้ใช้ตามจริงและไม่พยายามเลี่ยงสิทธิ์ด้วยการเปลี่ยนช่องทาง
192
+
193
+ ## 8. REST API เสริม
194
+
195
+ เมื่อ MCP ไม่มี tool ที่ต้องการ ใช้ REST API ด้วย token เดียวกัน:
196
+
197
+ | งาน | Endpoint |
198
+ |---|---|
199
+ | ข้อมูลผู้ใช้ | `GET /api/v1/auth/me` |
200
+ | โครงการ | `GET/POST /api/v1/projects`, `GET/PUT/DELETE /api/v1/projects/{id}` |
201
+ | สมาชิก | `GET/POST /api/v1/projects/{project}/members` |
202
+ | Phases | `GET/POST /api/v1/projects/{project}/phases` |
203
+ | งาน | `GET/POST /api/v1/projects/{project}/tasks`, `GET/PUT/DELETE /api/v1/tasks/{task}` |
204
+ | กำหนดการ/สถานะ | `PATCH /api/v1/tasks/{task}/schedule`, `PATCH /api/v1/tasks/{task}/status` |
205
+ | คอมเมนต์ | `GET/POST /api/v1/tasks/{task}/comments` |
206
+ | ไฟล์แนบ | `GET/POST /api/v1/tasks/{task}/attachments` |
207
+
208
+ REST ใช้การตรวจสิทธิ์ชุดเดียวกับ MCP และรูปแบบ JSON อยู่ใน `/docs/api` ของระบบ
209
+ รายละเอียดเพิ่มเติม: [references/rest-api.md](references/rest-api.md)
210
+
211
+ ## 9. สคริปต์ช่วยตรวจสอบ
212
+
213
+ `scripts/budhosp.mjs` ใช้ Node.js 18+ ไม่ต้องติดตั้ง dependency
214
+ ถ้าติดตั้งจาก npm ใช้ `npx budhosp-plan <command>` แทน path ด้านล่างได้ทั้งหมด
215
+
216
+ ```bash
217
+ # ตรวจ token + MCP tools + โครงการเริ่มต้น
218
+ node .agents/skills/budhosp-plan/scripts/budhosp.mjs check
219
+
220
+ # ค้นหาโครงการ
221
+ node .agents/skills/budhosp-plan/scripts/budhosp.mjs projects "HIS"
222
+
223
+ # ยืนยันโครงการและดู phases/members
224
+ node .agents/skills/budhosp-plan/scripts/budhosp.mjs project HIS-2026
225
+
226
+ # ดูงานในโครงการ
227
+ node .agents/skills/budhosp-plan/scripts/budhosp.mjs tasks HIS-2026 in_progress
228
+
229
+ # เรียก MCP tool ใดก็ได้ (ถ้าไม่ใส่ project จะเติม BUDHOSP_PROJECT ให้)
230
+ node .agents/skills/budhosp-plan/scripts/budhosp.mjs call get_project '{"project":"HIS-2026"}'
231
+ node .agents/skills/budhosp-plan/scripts/budhosp.mjs call create_task '{"project":"HIS-2026","title":"...","start_date":"2026-11-20","due_date":"2026-11-27"}'
232
+ ```
233
+
234
+ สคริปต์อ่านค่าจาก `BUDHOSP_BASE_URL`, `BUDHOSP_API_TOKEN`, `BUDHOSP_PROJECT`
235
+ และจะไม่พิมพ์ค่า token ออกมา
236
+
237
+ ## 10. Checklist ก่อนทำงานจริง
238
+
239
+ - [ ] ตั้ง `BUDHOSP_BASE_URL` และ `BUDHOSP_API_TOKEN` แล้ว และ token ไม่ได้อยู่ในไฟล์ที่ commit
240
+ - [ ] `node .agents/skills/budhosp-plan/scripts/budhosp.mjs check` ผ่าน (REST + MCP)
241
+ - [ ] ผู้ใช้ยืนยันโครงการเป้าหมาย (id หรือ code) แล้ว
242
+ - [ ] `get_project` สำเร็จ และเก็บ phases/members ไว้ใช้
243
+ - [ ] รู้ว่าบัญชีมีสิทธิ์ read หรือ write ในโครงการนั้น
244
+ - [ ] ถ้าจะเขียน: ตรวจงานเดิม, วันที่ถูกต้อง, และมีแผนจัดการกรณี timeout
@@ -0,0 +1,4 @@
1
+ # BUDHOSP Plan integration — copy to your project's .env (never commit real tokens)
2
+ BUDHOSP_BASE_URL=https://plan.example.go.th
3
+ BUDHOSP_API_TOKEN=
4
+ BUDHOSP_PROJECT=
@@ -0,0 +1,12 @@
1
+ {
2
+ "mcpServers": {
3
+ "budhosp-plan": {
4
+ "type": "http",
5
+ "url": "${BUDHOSP_BASE_URL}/mcp/projects",
6
+ "headers": {
7
+ "Authorization": "Bearer ${BUDHOSP_API_TOKEN}",
8
+ "Accept": "application/json, text/event-stream"
9
+ }
10
+ }
11
+ }
12
+ }
package/package.json ADDED
@@ -0,0 +1,37 @@
1
+ {
2
+ "name": "budhosp-plan",
3
+ "version": "1.0.0",
4
+ "description": "CLI and agent skill for connecting AI agents to BUDHOSP Plan via MCP or REST with a Sanctum API token and explicit project binding",
5
+ "type": "module",
6
+ "bin": {
7
+ "budhosp-plan": "scripts/budhosp.mjs"
8
+ },
9
+ "files": [
10
+ "SKILL.md",
11
+ "README.md",
12
+ "LICENSE",
13
+ "references",
14
+ "scripts",
15
+ "assets"
16
+ ],
17
+ "engines": {
18
+ "node": ">=18"
19
+ },
20
+ "keywords": [
21
+ "budhosp",
22
+ "mcp",
23
+ "project-management",
24
+ "ai-agent",
25
+ "agent-skill",
26
+ "sanctum"
27
+ ],
28
+ "license": "MIT",
29
+ "repository": {
30
+ "type": "git",
31
+ "url": "git+https://gitlab.com/klongchu/project-management-laravel.git"
32
+ },
33
+ "bugs": {
34
+ "url": "https://gitlab.com/klongchu/project-management-laravel/-/issues"
35
+ },
36
+ "homepage": "https://gitlab.com/klongchu/project-management-laravel/-/tree/main/docs/mcp/skills/budhosp-plan"
37
+ }
@@ -0,0 +1,99 @@
1
+ # REST API v1 Reference — BUDHOSP Plan
2
+
3
+ Base URL: `{BUDHOSP_BASE_URL}/api/v1`
4
+ การยืนยันตัวตน: `Authorization: Bearer <BUDHOSP_API_TOKEN>` (Sanctum)
5
+ OpenAPI แบบเต็ม: `{BUDHOSP_BASE_URL}/docs/api`
6
+
7
+ ทุก endpoint ที่ต้องยืนยันตัวตนจะอยู่หลัง middleware `auth:sanctum` และตรวจสิทธิ์ตามบทบาทของบัญชี
8
+
9
+ ## Auth
10
+
11
+ | Method | Path | คำอธิบาย |
12
+ |---|---|---|
13
+ | POST | `/auth/login` | ออก token (public) รับ `email`, `password`, `device_name` |
14
+ | POST | `/auth/logout` | เพิกถอน token ปัจจุบัน |
15
+ | GET | `/auth/me` | ข้อมูลผู้ใช้ปัจจุบัน (ใช้ตรวจ token) |
16
+
17
+ ## Projects
18
+
19
+ | Method | Path | คำอธิบาย |
20
+ |---|---|---|
21
+ | GET | `/projects` | รายการโครงการ (`search`, `status`, `sort`, `per_page` 1–100) |
22
+ | GET | `/projects/generate-code` | แนะนำ project code จากชื่อ |
23
+ | POST | `/projects` | สร้างโครงการ (ต้องมี `name`, `code`, `status`) |
24
+ | GET | `/projects/{project}` | รายละเอียดโครงการ (phases, members, tasks) |
25
+ | PUT | `/projects/{project}` | แก้ไขโครงการ |
26
+ | DELETE | `/projects/{project}` | ลบโครงการ (manager/admin) |
27
+ | GET | `/projects/{project}/gantt` | ข้อมูล Gantt |
28
+
29
+ `/projects` ค้นชื่อ, code และ description ได้ แต่ `/projects/{project}` รับเฉพาะ id
30
+
31
+ ## Members
32
+
33
+ | Method | Path | คำอธิบาย |
34
+ |---|---|---|
35
+ | GET | `/projects/{project}/members` | รายการสมาชิก |
36
+ | POST | `/projects/{project}/members` | เพิ่มสมาชิก |
37
+ | PATCH | `/projects/{project}/members/{user}/role` | เปลี่ยนบทบาท |
38
+ | DELETE | `/projects/{project}/members/{user}` | ลบสมาชิก |
39
+
40
+ ## Phases
41
+
42
+ | Method | Path | คำอธิบาย |
43
+ |---|---|---|
44
+ | GET | `/projects/{project}/phases` | รายการ phase |
45
+ | POST | `/projects/{project}/phases` | สร้าง phase |
46
+ | PUT | `/phases/{phase}` | แก้ไข phase |
47
+ | DELETE | `/phases/{phase}` | ลบ phase |
48
+
49
+ ## Tasks
50
+
51
+ | Method | Path | คำอธิบาย |
52
+ |---|---|---|
53
+ | GET | `/projects/{project}/tasks` | รายการงานในโครงการ |
54
+ | POST | `/projects/{project}/tasks` | สร้างงาน |
55
+ | GET | `/tasks/{task}` | รายละเอียดงาน |
56
+ | PUT | `/tasks/{task}` | แก้ไขงาน (ชื่อ, รายละเอียด, priority, assignees) |
57
+ | DELETE | `/tasks/{task}` | ลบงาน (manager) |
58
+ | PATCH | `/tasks/{task}/schedule` | เลื่อนวันเริ่ม/ครบกำหนด |
59
+ | PATCH | `/tasks/{task}/status` | เปลี่ยนสถานะ |
60
+ | POST | `/tasks/{task}/dependencies` | เพิ่ม dependency |
61
+ | DELETE | `/tasks/{task}/dependencies/{predecessor}` | ลบ dependency |
62
+
63
+ ## Subtasks, Comments, Attachments
64
+
65
+ | Method | Path | คำอธิบาย |
66
+ |---|---|---|
67
+ | POST | `/tasks/{task}/subtasks` | เพิ่ม subtask |
68
+ | PATCH | `/subtasks/{subtask}/toggle` | สลับสถานะ subtask |
69
+ | DELETE | `/subtasks/{subtask}` | ลบ subtask |
70
+ | GET/POST | `/tasks/{task}/comments` | ดู/เพิ่มคอมเมนต์ |
71
+ | GET/POST | `/tasks/{task}/attachments` | ดู/เพิ่มไฟล์แนบ |
72
+ | GET | `/attachments/{attachment}/download` | ดาวน์โหลดไฟล์แนบ |
73
+ | DELETE | `/attachments/{attachment}` | ลบไฟล์แนบ |
74
+
75
+ ## Notifications และ Admin
76
+
77
+ | Method | Path | คำอธิบาย |
78
+ |---|---|---|
79
+ | GET | `/notifications` | รายการแจ้งเตือน |
80
+ | PATCH | `/notifications/{id}/read` | ทำเครื่องหมายอ่านแล้ว |
81
+ | POST | `/notifications/read-all` | อ่านทั้งหมด |
82
+ | GET | `/admin/users` | จัดการผู้ใช้ (role `admin` เท่านั้น) |
83
+ | PATCH | `/admin/users/{user}/role` | เปลี่ยน role ระดับระบบ |
84
+ | PATCH | `/admin/users/{user}/status` | เปิด/ปิดบัญชี |
85
+
86
+ ## ตัวอย่าง
87
+
88
+ ```bash
89
+ # ตรวจ token
90
+ curl -s "$BUDHOSP_BASE_URL/api/v1/auth/me" -H "Authorization: Bearer $BUDHOSP_API_TOKEN"
91
+
92
+ # ค้นโครงการแล้วใช้ id ต่อ
93
+ curl -s "$BUDHOSP_BASE_URL/api/v1/projects?search=HIS" -H "Authorization: Bearer $BUDHOSP_API_TOKEN"
94
+
95
+ # งานที่ยังไม่เสร็จ
96
+ curl -s "$BUDHOSP_BASE_URL/api/v1/projects/12/tasks?status=in_progress" -H "Authorization: Bearer $BUDHOSP_API_TOKEN"
97
+ ```
98
+
99
+ REST API ใช้การตรวจสิทธิ์และข้อจำกัดเดียวกับ MCP — การเปลี่ยนช่องทางไม่ทำให้ได้สิทธิ์เพิ่ม
@@ -0,0 +1,156 @@
1
+ # Tools Reference — BUDHOSP Plan MCP
2
+
3
+ อ้างอิงจาก `app/Mcp/Tools/*` และ `app/Mcp/Servers/ProjectManagementServer.php`
4
+ สคีมาที่แท้จริงให้ยึดผลลัพธ์จาก `tools/list` ของ server ที่เชื่อมต่อ
5
+
6
+ ทุก tool ต้องมี Bearer token และผู้ใช้ต้องเป็นสมาชิกโครงการ (ยกเว้น `admin`)
7
+ `project` รับได้ทั้ง project id (ตัวเลข) และ project code (เช่น `HIS-2026`)
8
+
9
+ ## list_projects
10
+
11
+ อ่านรายการโครงการที่บัญชีเข้าถึงได้ เรียงจากสร้างล่าสุด
12
+
13
+ | Parameter | ชนิด | จำเป็น | คำอธิบาย |
14
+ |---|---|---|---|
15
+ | `search` | string | ไม่ | ค้นชื่อหรือ code |
16
+ | `status` | string | ไม่ | `planning` / `active` / `on_hold` / `completed` / `cancelled` |
17
+ | `limit` | integer | ไม่ | 1–100, ค่าเริ่มต้น 20 |
18
+
19
+ ผลลัพธ์:
20
+
21
+ ```json
22
+ {
23
+ "count": 2,
24
+ "projects": [
25
+ { "id": 12, "code": "HIS-2026", "name": "HIS Upgrade", "status": "active", "progress": 42, "start_date": "2026-01-05", "end_date": "2026-12-20" }
26
+ ]
27
+ }
28
+ ```
29
+
30
+ ## get_project
31
+
32
+ อ่านโครงการเดียว พร้อม phases, members และจำนวนงาน
33
+
34
+ | Parameter | ชนิด | จำเป็น | คำอธิบาย |
35
+ |---|---|---|---|
36
+ | `project` | string | ใช่ | project id หรือ project code |
37
+
38
+ ผลลัพธ์:
39
+
40
+ ```json
41
+ {
42
+ "project": { "id": 12, "code": "HIS-2026", "name": "HIS Upgrade", "status": "active", "progress": 42, "start_date": "2026-01-05", "end_date": "2026-12-20" },
43
+ "task_counts": { "total": 18, "done": 7 },
44
+ "phases": [{ "id": 3, "name": "Phase 1: Analysis", "color": "#3b82f6", "order_index": 1 }],
45
+ "members": [{ "id": 5, "name": "Somchai", "email": "somchai@example.go.th", "role": "member" }]
46
+ }
47
+ ```
48
+
49
+ ใช้ `phases[].id` เป็น `phase_id` และ `members[].id` เป็น `assignee_ids`
50
+ ค่า `phases` และ `members` อยู่ระดับเดียวกับ `project` ไม่ได้ซ้อนอยู่ใน `project`
51
+
52
+ ## list_tasks
53
+
54
+ อ่านงานในโครงการ พร้อมกรอง
55
+
56
+ | Parameter | ชนิด | จำเป็น | คำอธิบาย |
57
+ |---|---|---|---|
58
+ | `project` | string | ใช่ | project id หรือ project code |
59
+ | `status` | string | ไม่ | `todo` / `in_progress` / `in_review` / `done` |
60
+ | `priority` | string | ไม่ | `low` / `medium` / `high` / `urgent` |
61
+ | `phase_id` | integer | ไม่ | ต้องเป็น phase ของโครงการนี้ |
62
+ | `limit` | integer | ไม่ | 1–200, ค่าเริ่มต้น 50 |
63
+
64
+ ผลลัพธ์: `{ project, count, tasks[] }` โดยงานเรียงตาม `order_index` แล้ว `id`
65
+ `count` คือจำนวนที่คืนในครั้งนี้ ไม่ใช่จำนวนงานทั้งหมด และไม่มีการแบ่งหน้า
66
+
67
+ ## create_phase
68
+
69
+ สร้าง phase ต่อท้ายรายการ (ต้องเป็น manager หรือ admin)
70
+
71
+ | Parameter | ชนิด | จำเป็น | คำอธิบาย |
72
+ |---|---|---|---|
73
+ | `project` | string | ใช่ | project id หรือ project code |
74
+ | `name` | string | ใช่ | ชื่อ phase สูงสุด 255 ตัวอักษร |
75
+ | `color` | string | ไม่ | hex colour สูงสุด 20 ตัวอักษร ค่าเริ่มต้น `#3b82f6` |
76
+
77
+ ผลลัพธ์: `{ phase: { id, project_id, name, color, order_index } }`
78
+
79
+ ## create_task
80
+
81
+ สร้างงานในโครงการ (ต้องเป็น manager หรือ member)
82
+
83
+ | Parameter | ชนิด | จำเป็น | คำอธิบาย |
84
+ |---|---|---|---|
85
+ | `project` | string | ใช่ | project id หรือ project code |
86
+ | `title` | string | ใช่ | ชื่องาน สูงสุด 255 ตัวอักษร |
87
+ | `description` | string | ไม่ | รายละเอียด |
88
+ | `phase_id` | integer | ไม่ | ต้องเป็น phase ของโครงการนี้ |
89
+ | `start_date` | string | ใช่ | `YYYY-MM-DD` |
90
+ | `due_date` | string | ใช่ | `YYYY-MM-DD` และต้องไม่น้อยกว่า `start_date` |
91
+ | `priority` | string | ไม่ | `low` / `medium` / `high` / `urgent` |
92
+ | `status` | string | ไม่ | `todo` / `in_progress` / `in_review` / `done` |
93
+ | `progress` | integer | ไม่ | 0–100 |
94
+ | `is_milestone` | boolean | ไม่ | ระบุว่าเป็นหมุดหมาย |
95
+ | `assignee_ids` | integer[] | ไม่ | ต้องเป็นสมาชิกของโครงการนี้ |
96
+
97
+ ผลลัพธ์: `{ task }` ตาม `task` payload (`id`, `project_id`, `phase_id`, `title`, `status`,
98
+ `progress`, `priority`, `start_date`, `due_date`, `is_milestone`, `assignee_ids`)
99
+
100
+ ไม่มี idempotency key — ต้องตรวจงานเดิมก่อนสร้าง และตรวจซ้ำถ้า timeout
101
+
102
+ ## update_task_status
103
+
104
+ | Parameter | ชนิด | จำเป็น | คำอธิบาย |
105
+ |---|---|---|---|
106
+ | `task_id` | integer | ใช่ | id จาก `list_tasks` หรือ `create_task` |
107
+ | `status` | string | ใช่ | `todo` / `in_progress` / `in_review` / `done` |
108
+ | `order_index` | integer | ไม่ | ตำแหน่งเรียงบน Kanban (>= 0) |
109
+
110
+ ผลลัพธ์: `{ task }` พร้อมสถานะและ progress ที่ server ปรับแล้ว
111
+
112
+ ## update_task_schedule
113
+
114
+ | Parameter | ชนิด | จำเป็น | คำอธิบาย |
115
+ |---|---|---|---|
116
+ | `task_id` | integer | ใช่ | งานที่จะเลื่อน |
117
+ | `start_date` | string | ใช่ | `YYYY-MM-DD` |
118
+ | `due_date` | string | ใช่ | `YYYY-MM-DD` และ >= `start_date` |
119
+ | `progress` | integer | ไม่ | 0–100 ตั้งพร้อมกันได้ |
120
+
121
+ ผลลัพธ์: `{ task, shifted_tasks[] }` โดย `shifted_tasks` คืองานที่ถูกเลื่อนตาม
122
+ finish-to-start dependency ผ่าน `GanttScheduleService` (ไม่ใช่งานที่แก้โดยตรง)
123
+
124
+ ## update_task_progress
125
+
126
+ | Parameter | ชนิด | จำเป็น | คำอธิบาย |
127
+ |---|---|---|---|
128
+ | `task_id` | integer | ใช่ | งานที่จะอัปเดต |
129
+ | `progress` | integer | ใช่ | 0–100 |
130
+
131
+ ผลข้างเคียง:
132
+
133
+ - 100 → `status = done`
134
+ - 1–99 และสถานะเดิม `todo` → `in_progress`
135
+ - ลดจาก 100 ลงมาและสถานะเดิม `done` → `in_progress`
136
+
137
+ ผลลัพธ์: `{ task }` — อ่านค่าจริงหลังเขียนเสมอ
138
+
139
+ ## add_task_comment
140
+
141
+ | Parameter | ชนิด | จำเป็น | คำอธิบาย |
142
+ |---|---|---|---|
143
+ | `task_id` | integer | ใช่ | งานที่จะคอมเมนต์ |
144
+ | `content` | string | ใช่ | ข้อความ plain text สูงสุด 5000 ตัวอักษร |
145
+
146
+ ผลลัพธ์: `{ comment: { id, task_id, user_id, content, created_at } }`
147
+
148
+ ## ข้อจำกัดที่ MCP ไม่รองรับ
149
+
150
+ - ลบโครงการ งาน สมาชิก หรือ phase
151
+ - แก้ชื่อ/รายละเอียด/ผู้รับผิดชอบ/priority/phase ของงานที่มีอยู่
152
+ - จัดการ dependencies, subtasks, attachments, notifications
153
+ - อ่าน activity log
154
+ - ออกหรือเพิกถอน token
155
+
156
+ ใช้ REST API หรือหน้าเว็บตามสิทธิ์ของบัญชี
@@ -0,0 +1,589 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * BUDHOSP Plan helper (MCP + REST API).
4
+ *
5
+ * Requires Node.js 18+ (global fetch). No external dependencies.
6
+ *
7
+ * Environment:
8
+ * BUDHOSP_BASE_URL e.g. https://project.example.go.th
9
+ * BUDHOSP_API_TOKEN Sanctum bearer token (fallback: BUDHOSP_TOKEN, BUDHOSP_MCP_TOKEN)
10
+ * BUDHOSP_PROJECT default project id or code (recommended)
11
+ *
12
+ * Usage:
13
+ * node scripts/budhosp.mjs check
14
+ * node scripts/budhosp.mjs projects [search]
15
+ * node scripts/budhosp.mjs project [id|code]
16
+ * node scripts/budhosp.mjs project code:12345
17
+ * node scripts/budhosp.mjs tasks [id|code] [status]
18
+ * node scripts/budhosp.mjs tools
19
+ * node scripts/budhosp.mjs call <tool> [json-arguments]
20
+ */
21
+
22
+ const BASE_URL = String(process.env.BUDHOSP_BASE_URL || '').trim().replace(/\/+$/, '');
23
+ const TOKEN = String(
24
+ process.env.BUDHOSP_API_TOKEN ||
25
+ process.env.BUDHOSP_TOKEN ||
26
+ process.env.BUDHOSP_MCP_TOKEN ||
27
+ '',
28
+ ).trim();
29
+ const DEFAULT_PROJECT = String(process.env.BUDHOSP_PROJECT || '').trim();
30
+
31
+ const MCP_PROTOCOL_VERSION = '2025-06-18';
32
+ const PROJECT_SCOPED_TOOLS = new Set(['get_project', 'list_tasks', 'create_phase', 'create_task']);
33
+
34
+ let mcpSessionId = null;
35
+ let mcpInitialized = false;
36
+ let mcpNextId = 1;
37
+
38
+ function fail(message, code = 1) {
39
+ console.error(`ERROR: ${message}`);
40
+ process.exit(code);
41
+ }
42
+
43
+ function requireConfig(needsProject = false) {
44
+ if (!BASE_URL) {
45
+ fail('ยังไม่ได้ตั้งค่า BUDHOSP_BASE_URL เช่น https://project.example.go.th');
46
+ }
47
+ if (!TOKEN) {
48
+ fail('ยังไม่ได้ตั้งค่า BUDHOSP_API_TOKEN (Sanctum bearer token)');
49
+ }
50
+ if (needsProject && !DEFAULT_PROJECT) {
51
+ fail('ยังไม่ได้ตั้งค่า BUDHOSP_PROJECT (project id หรือ project code) หรือส่งค่ามาในคำสั่ง');
52
+ }
53
+ }
54
+
55
+ function print(value) {
56
+ console.log(JSON.stringify(value, null, 2));
57
+ }
58
+
59
+ function describeHttpError(status, path, body) {
60
+ const detail =
61
+ body && typeof body === 'object'
62
+ ? body.message || JSON.stringify(body)
63
+ : String(body || '').slice(0, 500);
64
+
65
+ if (status === 401) {
66
+ return `HTTP 401 ที่ ${path}: token ไม่ถูกต้อง หมดอายุ หรือถูกเพิกถอน — ขอ token ใหม่ (${detail})`;
67
+ }
68
+ if (status === 403) {
69
+ return `HTTP 403 ที่ ${path}: บัญชีไม่มีสิทธิ์ในโครงการนี้ — หยุดเขียนและแจ้งผู้ใช้ (${detail})`;
70
+ }
71
+ if (status === 404) {
72
+ return `HTTP 404 ที่ ${path}: ไม่พบโครงการหรืองาน — ตรวจ id/code จากรายการจริง (${detail})`;
73
+ }
74
+ if (status === 422) {
75
+ return `HTTP 422 ที่ ${path}: ข้อมูลไม่ผ่าน validation (${detail})`;
76
+ }
77
+ if (status === 429) {
78
+ return `HTTP 429 ที่ ${path}: ถูกจำกัดความถี่ — รอและลดจำนวนคำขอ (${detail})`;
79
+ }
80
+ return `HTTP ${status} ที่ ${path}: ${detail}`;
81
+ }
82
+
83
+ async function requestJson(path, options = {}) {
84
+ let response;
85
+ try {
86
+ response = await fetch(`${BASE_URL}${path}`, {
87
+ ...options,
88
+ headers: {
89
+ Authorization: `Bearer ${TOKEN}`,
90
+ Accept: 'application/json',
91
+ 'Content-Type': 'application/json',
92
+ ...(options.headers || {}),
93
+ },
94
+ signal: AbortSignal.timeout(30000),
95
+ });
96
+ } catch (error) {
97
+ fail(`เชื่อมต่อ ${BASE_URL}${path} ไม่สำเร็จ: ${error.message}`);
98
+ }
99
+
100
+ const text = await response.text();
101
+ let body = null;
102
+ if (text.trim()) {
103
+ try {
104
+ body = JSON.parse(text);
105
+ } catch {
106
+ body = text;
107
+ }
108
+ }
109
+
110
+ if (!response.ok) {
111
+ fail(describeHttpError(response.status, path, body));
112
+ }
113
+
114
+ return body;
115
+ }
116
+
117
+ function parseRpcPayload(text, expectedId) {
118
+ const trimmed = text.trim();
119
+ if (!trimmed) {
120
+ return null;
121
+ }
122
+
123
+ if (trimmed.startsWith('{') || trimmed.startsWith('[')) {
124
+ const parsed = JSON.parse(trimmed);
125
+ return Array.isArray(parsed) ? parsed[parsed.length - 1] : parsed;
126
+ }
127
+
128
+ const events = trimmed.split(/\r?\n\r?\n/);
129
+ let fallback = null;
130
+ for (const event of events) {
131
+ const data = event
132
+ .split(/\r?\n/)
133
+ .filter((line) => line.startsWith('data:'))
134
+ .map((line) => line.slice(5).trim())
135
+ .join('\n');
136
+ if (!data) {
137
+ continue;
138
+ }
139
+ try {
140
+ const message = JSON.parse(data);
141
+ if (expectedId === undefined || message.id === expectedId) {
142
+ return message;
143
+ }
144
+ fallback = message;
145
+ } catch {
146
+ // Ignore non-JSON SSE frames.
147
+ }
148
+ }
149
+
150
+ return fallback;
151
+ }
152
+
153
+ async function mcpPost(payload) {
154
+ const headers = {
155
+ Authorization: `Bearer ${TOKEN}`,
156
+ Accept: 'application/json, text/event-stream',
157
+ 'Content-Type': 'application/json',
158
+ };
159
+ if (mcpInitialized) {
160
+ headers['MCP-Protocol-Version'] = MCP_PROTOCOL_VERSION;
161
+ }
162
+ if (mcpSessionId) {
163
+ headers['Mcp-Session-Id'] = mcpSessionId;
164
+ }
165
+
166
+ let response;
167
+ try {
168
+ response = await fetch(`${BASE_URL}/mcp/projects`, {
169
+ method: 'POST',
170
+ headers,
171
+ body: JSON.stringify(payload),
172
+ signal: AbortSignal.timeout(30000),
173
+ });
174
+ } catch (error) {
175
+ fail(`เชื่อมต่อ MCP ${BASE_URL}/mcp/projects ไม่สำเร็จ: ${error.message}`);
176
+ }
177
+
178
+ const sessionId = response.headers.get('mcp-session-id');
179
+ if (sessionId) {
180
+ mcpSessionId = sessionId;
181
+ }
182
+
183
+ const text = await response.text();
184
+
185
+ if (!response.ok) {
186
+ let body = text;
187
+ try {
188
+ body = JSON.parse(text);
189
+ } catch {
190
+ // Keep raw text.
191
+ }
192
+ fail(describeHttpError(response.status, '/mcp/projects', body));
193
+ }
194
+
195
+ return parseRpcPayload(text, payload.id);
196
+ }
197
+
198
+ async function openMcpSession() {
199
+ if (mcpInitialized) {
200
+ return;
201
+ }
202
+
203
+ const init = await mcpPost({
204
+ jsonrpc: '2.0',
205
+ id: mcpNextId++,
206
+ method: 'initialize',
207
+ params: {
208
+ protocolVersion: MCP_PROTOCOL_VERSION,
209
+ capabilities: {},
210
+ clientInfo: { name: 'budhosp-plan-skill', version: '1.0.0' },
211
+ },
212
+ });
213
+
214
+ if (!init || init.error) {
215
+ fail(`MCP initialize ไม่สำเร็จ: ${JSON.stringify(init && init.error ? init.error : init)}`);
216
+ }
217
+
218
+ mcpInitialized = true;
219
+
220
+ await mcpPost({
221
+ jsonrpc: '2.0',
222
+ method: 'notifications/initialized',
223
+ params: {},
224
+ });
225
+ }
226
+
227
+ async function mcpRequest(method, params) {
228
+ await openMcpSession();
229
+ const id = mcpNextId++;
230
+ const message = await mcpPost({ jsonrpc: '2.0', id, method, params });
231
+
232
+ if (!message) {
233
+ fail(`MCP ${method} ไม่ได้รับผลลัพธ์`);
234
+ }
235
+ if (message.error) {
236
+ const error = message.error;
237
+ const text = error.message || JSON.stringify(error);
238
+ if (/unauth|token|401/i.test(text)) {
239
+ fail(`MCP unauthorized: ${text}`);
240
+ }
241
+ fail(`MCP error (${error.code || 'unknown'}): ${text}`);
242
+ }
243
+
244
+ return message.result;
245
+ }
246
+
247
+ async function listTools() {
248
+ const result = await mcpRequest('tools/list', {});
249
+ const tools = result && Array.isArray(result.tools) ? result.tools : [];
250
+ return tools.map((tool) => tool.name).filter(Boolean);
251
+ }
252
+
253
+ function parseToolContent(result) {
254
+ if (!result) {
255
+ return null;
256
+ }
257
+ if (result.structuredContent !== undefined) {
258
+ return result.structuredContent;
259
+ }
260
+
261
+ const content = Array.isArray(result.content) ? result.content : [];
262
+ const values = content
263
+ .filter((part) => part && part.type === 'text')
264
+ .map((part) => {
265
+ try {
266
+ return JSON.parse(part.text);
267
+ } catch {
268
+ return part.text;
269
+ }
270
+ });
271
+
272
+ if (values.length === 0) {
273
+ return result;
274
+ }
275
+
276
+ return values.length === 1 ? values[0] : values;
277
+ }
278
+
279
+ function argumentsObject(args) {
280
+ if (!args) {
281
+ return {};
282
+ }
283
+ if (typeof args === 'string') {
284
+ if (!args.trim()) {
285
+ return {};
286
+ }
287
+ try {
288
+ const parsed = JSON.parse(args);
289
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
290
+ fail('arguments ต้องเป็น JSON object');
291
+ }
292
+ return parsed;
293
+ } catch (error) {
294
+ fail(`arguments ไม่ใช่ JSON ที่ถูกต้อง: ${error.message}`);
295
+ }
296
+ }
297
+ return args;
298
+ }
299
+
300
+ async function callTool(name, args) {
301
+ if (!name) {
302
+ fail('ต้องระบุชื่อ tool');
303
+ }
304
+
305
+ const toolArgs = { ...argumentsObject(args) };
306
+ if (PROJECT_SCOPED_TOOLS.has(name) && toolArgs.project === undefined) {
307
+ if (DEFAULT_PROJECT) {
308
+ toolArgs.project = DEFAULT_PROJECT;
309
+ } else {
310
+ fail(`${name} ต้องระบุ project (id หรือ code) หรือตั้งค่า BUDHOSP_PROJECT`);
311
+ }
312
+ }
313
+
314
+ const result = await mcpRequest('tools/call', { name, arguments: toolArgs });
315
+ return parseToolContent(result);
316
+ }
317
+
318
+ function summarizeProject(project) {
319
+ if (!project) {
320
+ return null;
321
+ }
322
+ return {
323
+ id: project.id,
324
+ code: project.code,
325
+ name: project.name,
326
+ status: project.status,
327
+ progress: project.progress,
328
+ start_date: project.start_date,
329
+ end_date: project.end_date,
330
+ };
331
+ }
332
+
333
+ async function restProjectList(search) {
334
+ const projects = [];
335
+ const maxPages = 20;
336
+
337
+ for (let page = 1; page <= maxPages; page += 1) {
338
+ const query = new URLSearchParams({ per_page: '100', page: String(page) });
339
+ if (search) {
340
+ query.set('search', search);
341
+ }
342
+ const body = await requestJson(`/api/v1/projects?${query.toString()}`);
343
+ const data = Array.isArray(body && body.data) ? body.data : [];
344
+ projects.push(...data);
345
+
346
+ const lastPage = body && body.meta ? Number(body.meta.last_page) : NaN;
347
+ if (data.length < 100 || (Number.isFinite(lastPage) && page >= lastPage)) {
348
+ break;
349
+ }
350
+ }
351
+
352
+ return projects;
353
+ }
354
+
355
+ async function resolveProject(reference) {
356
+ let identifier = String(reference || DEFAULT_PROJECT || '').trim();
357
+ if (!identifier) {
358
+ fail('ต้องระบุ project id หรือ project code (หรือตั้งค่า BUDHOSP_PROJECT)');
359
+ }
360
+
361
+ const explicitCode = /^code:/i.test(identifier);
362
+ if (explicitCode) {
363
+ identifier = identifier.slice(5).trim();
364
+ if (!identifier) {
365
+ fail('รูปแบบ code:<project code> ไม่ถูกต้อง');
366
+ }
367
+ }
368
+
369
+ if (!explicitCode && /^\d+$/.test(identifier)) {
370
+ const body = await requestJson(`/api/v1/projects/${encodeURIComponent(identifier)}`);
371
+ if (!body || !body.data) {
372
+ fail(`ไม่พบโครงการ id ${identifier}`);
373
+ }
374
+ return body.data;
375
+ }
376
+
377
+ let projects = await restProjectList(identifier);
378
+ if (projects.length === 0) {
379
+ projects = await restProjectList();
380
+ }
381
+ const needle = identifier.toLowerCase();
382
+ const exactCode = projects.filter((project) => String(project.code || '').toLowerCase() === needle);
383
+ const exactName = projects.filter((project) => String(project.name || '').toLowerCase() === needle);
384
+ const partial = projects.filter((project) => {
385
+ const code = String(project.code || '').toLowerCase();
386
+ const name = String(project.name || '').toLowerCase();
387
+ return code.includes(needle) || name.includes(needle);
388
+ });
389
+
390
+ let match = null;
391
+ if (exactCode.length === 1) {
392
+ match = exactCode[0];
393
+ } else if (exactName.length === 1) {
394
+ match = exactName[0];
395
+ }
396
+
397
+ if (exactCode.length > 1 || exactName.length > 1) {
398
+ fail(
399
+ `พบหลายโครงการที่ตรงกับ "${identifier}": ${projects
400
+ .map((project) => `${project.code} (id ${project.id})`)
401
+ .join(', ')} — ให้ผู้ใช้ระบุ code ที่ต้องการ`,
402
+ );
403
+ }
404
+
405
+ if (!match && partial.length > 0) {
406
+ fail(
407
+ `ไม่พบ code หรือชื่อโครงการที่ตรงทั้งหมดกับ "${identifier}". โครงการที่ใกล้เคียง: ${partial
408
+ .map((project) => `${project.code} (id ${project.id})`)
409
+ .join(', ')} — ให้ผู้ใช้ยืนยัน code`,
410
+ );
411
+ }
412
+
413
+ if (!match) {
414
+ fail(
415
+ `ไม่พบโครงการ "${identifier}". โครงการที่เข้าถึงได้: ${projects
416
+ .map((project) => `${project.code} (id ${project.id})`)
417
+ .join(', ') || 'ไม่มี'}`,
418
+ );
419
+ }
420
+
421
+ const body = await requestJson(`/api/v1/projects/${encodeURIComponent(match.id)}`);
422
+ return body && body.data ? body.data : match;
423
+ }
424
+
425
+ async function cmdCheck() {
426
+ requireConfig();
427
+ const me = await requestJson('/api/v1/auth/me');
428
+ const user = me && me.data ? me.data : me;
429
+
430
+ const toolNames = await listTools();
431
+
432
+ const summary = {
433
+ base_url: BASE_URL,
434
+ user: user
435
+ ? {
436
+ id: user.id,
437
+ name: user.name,
438
+ email: user.email,
439
+ role: user.role || null,
440
+ }
441
+ : null,
442
+ mcp: { endpoint: `${BASE_URL}/mcp/projects`, tools: toolNames },
443
+ project: null,
444
+ };
445
+
446
+ if (DEFAULT_PROJECT) {
447
+ const payload = await callTool('get_project', { project: DEFAULT_PROJECT });
448
+ const project = payload && payload.project ? payload.project : null;
449
+ summary.project = {
450
+ ...(summarizeProject(payload && payload.project) || {}),
451
+ phases: payload && Array.isArray(payload.phases) ? payload.phases.map((phase) => phase.name) : [],
452
+ member_count: payload && Array.isArray(payload.members) ? payload.members.length : 0,
453
+ task_counts: (payload && payload.task_counts) || null,
454
+ };
455
+ if (!project) {
456
+ summary.project = payload;
457
+ }
458
+ } else {
459
+ summary.note = 'ยังไม่ได้ตั้งค่า BUDHOSP_PROJECT — ระบุ project id/code ก่อนใช้งาน';
460
+ }
461
+
462
+ print(summary);
463
+ }
464
+
465
+ async function cmdProjects(search) {
466
+ requireConfig();
467
+ const projects = await restProjectList(search);
468
+ print({
469
+ count: projects.length,
470
+ projects: projects.map(summarizeProject),
471
+ });
472
+ }
473
+
474
+ async function cmdProject(reference) {
475
+ requireConfig(Boolean(!reference && !DEFAULT_PROJECT));
476
+ const project = await resolveProject(reference);
477
+ print({
478
+ project: summarizeProject(project),
479
+ phases: Array.isArray(project.phases)
480
+ ? project.phases.map((phase) => ({ id: phase.id, name: phase.name, order_index: phase.order_index }))
481
+ : [],
482
+ members: Array.isArray(project.members)
483
+ ? project.members.map((member) => ({
484
+ id: member.id,
485
+ name: member.name,
486
+ email: member.email,
487
+ role: member.pivot ? member.pivot.role : member.role,
488
+ }))
489
+ : [],
490
+ });
491
+ }
492
+
493
+ async function cmdTasks(reference, status) {
494
+ requireConfig(Boolean(!reference && !DEFAULT_PROJECT));
495
+ const project = await resolveProject(reference);
496
+ const query = new URLSearchParams({ per_page: '100' });
497
+ if (status) {
498
+ query.set('status', status);
499
+ }
500
+ const body = await requestJson(`/api/v1/projects/${encodeURIComponent(project.id)}/tasks?${query.toString()}`);
501
+ const tasks = Array.isArray(body && body.data) ? body.data : [];
502
+ print({
503
+ project: summarizeProject(project),
504
+ count: tasks.length,
505
+ tasks: tasks.map((task) => ({
506
+ id: task.id,
507
+ title: task.title,
508
+ status: task.status,
509
+ progress: task.progress,
510
+ priority: task.priority,
511
+ phase_id: task.phase_id,
512
+ start_date: task.start_date,
513
+ due_date: task.due_date,
514
+ })),
515
+ });
516
+ }
517
+
518
+ async function cmdTools() {
519
+ requireConfig();
520
+ const toolNames = await listTools();
521
+ print({ count: toolNames.length, tools: toolNames });
522
+ }
523
+
524
+ async function cmdCall(name, args) {
525
+ requireConfig();
526
+ const result = await callTool(name, args);
527
+ print(result);
528
+ }
529
+
530
+ function printUsage() {
531
+ console.log(`BUDHOSP Plan helper
532
+
533
+ Environment:
534
+ BUDHOSP_BASE_URL required, e.g. https://project.example.go.th
535
+ BUDHOSP_API_TOKEN required, Sanctum bearer token
536
+ BUDHOSP_PROJECT default project id or code
537
+
538
+ Commands:
539
+ check verify REST auth, MCP tools and default project
540
+ projects [search] list accessible projects
541
+ project [id|code] resolve one project with phases and members
542
+ (use code:<code> when the code is numeric)
543
+ tasks [id|code] [status] list tasks in a project
544
+ tools list MCP tool names
545
+ call <tool> [json] call an MCP tool (project is injected when configured)`);
546
+ }
547
+
548
+ async function main() {
549
+ const [command, ...args] = process.argv.slice(2);
550
+
551
+ if (!command || command === 'help' || command === '--help' || command === '-h') {
552
+ printUsage();
553
+ return;
554
+ }
555
+
556
+ if (typeof fetch !== 'function') {
557
+ fail('ต้องใช้ Node.js 18 ขึ้นไป (ไม่พบ global fetch)');
558
+ }
559
+
560
+ switch (command) {
561
+ case 'check':
562
+ await cmdCheck();
563
+ break;
564
+ case 'projects':
565
+ await cmdProjects(args[0]);
566
+ break;
567
+ case 'project':
568
+ await cmdProject(args[0]);
569
+ break;
570
+ case 'tasks':
571
+ await cmdTasks(args[0], args[1]);
572
+ break;
573
+ case 'tools':
574
+ await cmdTools();
575
+ break;
576
+ case 'call':
577
+ if (!args[0]) {
578
+ fail('usage: node scripts/budhosp.mjs call <tool> [json]');
579
+ }
580
+ await cmdCall(args[0], args[1]);
581
+ break;
582
+ default:
583
+ fail(`ไม่รู้จักคำสั่ง "${command}" — ใช้ help`);
584
+ }
585
+ }
586
+
587
+ main().catch((error) => {
588
+ fail(error && error.message ? error.message : String(error));
589
+ });