@rolling-design-sync/mcp 0.0.0-stage → 0.13.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/LICENSE +202 -0
- package/README.md +201 -2
- package/bin/rds-mcp.js +9 -0
- package/package.json +51 -4
- package/src/client.js +53 -0
- package/src/config.js +69 -0
- package/src/server.js +201 -0
- package/src/tools.js +176 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
package/README.md
CHANGED
|
@@ -1,3 +1,202 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @rolling-design-sync/mcp
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
A local (stdio) [MCP](https://modelcontextprotocol.io) server over the
|
|
4
|
+
[Rolling Design Sync](https://github.com/deven-bryant/rolling-design-sync)
|
|
5
|
+
**v3** API, so any MCP-capable coding agent (Claude Code, Cursor,
|
|
6
|
+
Windsurf, Devin, …) can list what changed in Figma since it was last built,
|
|
7
|
+
lease work, and clear implemented nodes without a bespoke CLI. It talks to
|
|
8
|
+
whatever API `RDS_API_BASE_URL` points at (self-hosted, `RDS_STORE=local`, or
|
|
9
|
+
hosted).
|
|
10
|
+
|
|
11
|
+
## How tools are discovered
|
|
12
|
+
|
|
13
|
+
The server has no hand-written tools. At startup it fetches
|
|
14
|
+
`${RDS_API_BASE_URL}/v3/openapi.json` and registers one tool per operation
|
|
15
|
+
annotated `x-rds-mcp: { tool: "<name>" }`:
|
|
16
|
+
|
|
17
|
+
- **Name** — the annotation's `tool`; **title** — the operation's `summary`;
|
|
18
|
+
**description** — its `summary` and `description` (written for models).
|
|
19
|
+
- **Input schema** — the operation's path and query parameters plus the
|
|
20
|
+
properties of its JSON body, with their JSON Schemas passed through as-is
|
|
21
|
+
(a body that isn't an object, or whose properties collide with a parameter
|
|
22
|
+
name, becomes one `body` input).
|
|
23
|
+
- **Calls** map the inputs back onto the HTTP request (path, query, body) with
|
|
24
|
+
the agent token and `X-RDS-Client: mcp/<version>`. JSON responses are
|
|
25
|
+
returned as JSON text; `format=ndjson|md` responses as the API's text.
|
|
26
|
+
- **Errors** come back as tool errors built from the v3 problem:
|
|
27
|
+
`HTTP <status> <method> <path> — <title> (<code>): <detail>`, then the API's
|
|
28
|
+
`Hint:` line (and `Valid parameters:` when it lists them). Inputs the tool
|
|
29
|
+
doesn't take are rejected before any request is sent.
|
|
30
|
+
|
|
31
|
+
Operations without the annotation (the plugin routes, `openapi.json`) are
|
|
32
|
+
never exposed. If the API can't be reached, answers with something other than
|
|
33
|
+
an OpenAPI document, or lists no annotated operations, the server exits with a
|
|
34
|
+
message naming `RDS_API_BASE_URL` instead of starting with no tools.
|
|
35
|
+
|
|
36
|
+
**The tool set follows the connected server's version:** an older or newer
|
|
37
|
+
API simply yields a different set of tools, with that server's schemas and
|
|
38
|
+
descriptions. Nothing in this package needs to change when the API adds or
|
|
39
|
+
changes an operation.
|
|
40
|
+
|
|
41
|
+
### Figma links and defaults
|
|
42
|
+
|
|
43
|
+
- Every tool whose route takes `fileKey` / `nodeId` also takes a Figma link as
|
|
44
|
+
`url` (`https://www.figma.com/design/<fileKey>/…?node-id=1-2`); the server
|
|
45
|
+
then sends `-` for those path parameters and lets the API read the link, so
|
|
46
|
+
`fileKey` and `nodeId` are optional there.
|
|
47
|
+
- Wherever a node id is expected (`nodeId`, `under`, `nodeIds[]`, including
|
|
48
|
+
inside the body such as `clear_nodes` `items[].nodeId`), a Figma link with a
|
|
49
|
+
`node-id` is accepted and turned into the node id; with no `fileKey` / `url`,
|
|
50
|
+
the file key comes from those links (all must name the same file).
|
|
51
|
+
- Otherwise `fileKey` defaults to `RDS_FILE_KEY`.
|
|
52
|
+
|
|
53
|
+
## Tools (as of this API version)
|
|
54
|
+
|
|
55
|
+
The tools the current `apps/api` exposes (`GET /v3/openapi.json` is the source
|
|
56
|
+
of truth; a different server version may list more or fewer):
|
|
57
|
+
|
|
58
|
+
| Tool | Route | What it is for |
|
|
59
|
+
|------|-------|----------------|
|
|
60
|
+
| `list_files` | `GET /v3/files` | The tracked files. |
|
|
61
|
+
| `get_file` | `GET /v3/files/{fileKey}` | One file with its counts. |
|
|
62
|
+
| `list_scopes` | `GET /v3/files/{fileKey}/scopes` | The synced scopes (sections / frames) of a file. |
|
|
63
|
+
| `list_nodes` | `GET /v3/files/{fileKey}/nodes` | The work queue (dirty nodes by default) with each node's `changes`, `contentHash`, `claim` and `figmaUrl`; filters, `q`, `fields`, `cursor` paging, `format`. |
|
|
64
|
+
| `get_node` | `GET /v3/files/{fileKey}/nodes/{nodeId}` | One node with its `changes`, counts and history; re-read a `stale` node here. |
|
|
65
|
+
| `resolve_url` | `GET /v3/resolve` | A Figma link → `{ fileKey, nodeId }`. |
|
|
66
|
+
| `summarize` | `GET /v3/files/{fileKey}/summary` | Counts of what changed, by category, type and component. |
|
|
67
|
+
| `list_work_items` | `GET /v3/files/{fileKey}/work` | Changes grouped into work items (e.g. one per component). |
|
|
68
|
+
| `get_trends` | `GET /v3/insights/trends` | Nodes cleared and newly dirtied in the last `windowDays` days, per file and in total. |
|
|
69
|
+
| `claim_nodes` | `POST /v3/files/{fileKey}/claims` | Lease nodes (by `nodeIds` or `filter`) to a `worker`. |
|
|
70
|
+
| `renew_claim` | `POST /v3/files/{fileKey}/claims/{claimId}/renew` | Extend a lease. |
|
|
71
|
+
| `release_claim` | `DELETE /v3/files/{fileKey}/claims/{claimId}` | Hand back what a claim still holds. |
|
|
72
|
+
| `clear_nodes` | `POST /v3/files/{fileKey}/clear` | Bulk, hash-guarded clear of implemented nodes; each item `cleared`, `stale` or `not_found`. |
|
|
73
|
+
| `block_node` | `POST /v3/files/{fileKey}/nodes/{nodeId}/block` | Mark a node you can't implement, with a reason. |
|
|
74
|
+
| `unblock_node` | `POST /v3/files/{fileKey}/nodes/{nodeId}/unblock` | Undo a block. |
|
|
75
|
+
| `list_events` | `GET /v3/files/{fileKey}/events` | The file's activity log (syncs, clears, claims, blocks), paged with `after`. |
|
|
76
|
+
|
|
77
|
+
The pre-v3 tools `get_design_delta` and `clear_node` are gone; use
|
|
78
|
+
`list_nodes` (with `under`) / `claim_nodes` and `clear_nodes`.
|
|
79
|
+
|
|
80
|
+
The loop the server instructions teach the agent:
|
|
81
|
+
|
|
82
|
+
1. `list_nodes` for the screen or component being worked on (or `claim_nodes`
|
|
83
|
+
when several agents share a file; `summarize` / `list_work_items` for an
|
|
84
|
+
overview).
|
|
85
|
+
2. Implement each node's `changes` — what changed since it was built — mapping
|
|
86
|
+
it to code via Code Connect / `figma.ts` mappings where present, and pulling
|
|
87
|
+
live details for **that node only** from the Figma MCP via its `figmaUrl`.
|
|
88
|
+
3. `clear_nodes` with the `nodeId` + `contentHash` pairs it read and the commit
|
|
89
|
+
SHA. On `stale`, re-read that node with `get_node` and implement the newer
|
|
90
|
+
change; never retry the old hash. `block_node` what can't be implemented.
|
|
91
|
+
|
|
92
|
+
`nodeId` is a Figma node id such as `1:2`; the `1-2` form from a Figma link is
|
|
93
|
+
accepted too. The file key is the `<fileKey>` in `figma.com/design/<fileKey>/…`.
|
|
94
|
+
|
|
95
|
+
## Example session
|
|
96
|
+
|
|
97
|
+
```text
|
|
98
|
+
> list_nodes { "url": "https://www.figma.com/design/AbCdEf123456/App?node-id=2-1", "fields": "nodeId,name,changeType,changes,contentHash" }
|
|
99
|
+
{ "fileKey": "AbCdEf123456", "total": 2, "nextCursor": null, "nodes": [
|
|
100
|
+
{ "nodeId": "2:1", "name": "Card", "changeType": "modified", "contentHash": "9f…",
|
|
101
|
+
"changes": { "paddingLeft": { "built": 12, "now": 16, "category": "layout" } } },
|
|
102
|
+
{ "nodeId": "2:5", "name": "Title", "changeType": "modified", "contentHash": "4c…",
|
|
103
|
+
"changes": { "fontSize": { "built": 14, "now": 16, "category": "typography" } } } ] }
|
|
104
|
+
|
|
105
|
+
… agent edits Card.tsx and Title.tsx, commits 1a2b3c4 …
|
|
106
|
+
|
|
107
|
+
> clear_nodes { "fileKey": "AbCdEf123456", "commitRef": "1a2b3c4",
|
|
108
|
+
"items": [ { "nodeId": "2:1", "contentHash": "9f…" }, { "nodeId": "2:5", "contentHash": "4c…" } ] }
|
|
109
|
+
{ "fileKey": "AbCdEf123456", "totals": { "cleared": 1, "stale": 1, "notFound": 0 }, "results": [
|
|
110
|
+
{ "nodeId": "2:1", "status": "cleared", "contentHash": "9f…" },
|
|
111
|
+
{ "nodeId": "2:5", "status": "stale", "contentHash": "7d…" } ] }
|
|
112
|
+
|
|
113
|
+
> get_node { "fileKey": "AbCdEf123456", "nodeId": "2:5", "fields": "changes,contentHash" }
|
|
114
|
+
{ "fileKey": "AbCdEf123456", "contentHash": "7d…",
|
|
115
|
+
"changes": { "fontSize": { "built": 14, "now": 18, "category": "typography" } } }
|
|
116
|
+
|
|
117
|
+
… agent updates Title.tsx, commits 5e6f7a8 …
|
|
118
|
+
|
|
119
|
+
> clear_nodes { "fileKey": "AbCdEf123456", "commitRef": "5e6f7a8", "items": [ { "nodeId": "2:5", "contentHash": "7d…" } ] }
|
|
120
|
+
{ "fileKey": "AbCdEf123456", "totals": { "cleared": 1, "stale": 0, "notFound": 0 }, "results": [ … ] }
|
|
121
|
+
|
|
122
|
+
> get_node { "fileKey": "AbCdEf123456", "nodeId": "9:9" }
|
|
123
|
+
HTTP 404 GET /v3/files/AbCdEf123456/nodes/9%3A9 — Node not found (node_not_found): …
|
|
124
|
+
Hint: …
|
|
125
|
+
```
|
|
126
|
+
|
|
127
|
+
## Environment
|
|
128
|
+
|
|
129
|
+
| Variable | Required | Meaning |
|
|
130
|
+
|----------|----------|---------|
|
|
131
|
+
| `RDS_API_BASE_URL` | yes | API origin, e.g. `http://127.0.0.1:8787`. |
|
|
132
|
+
| `RDS_AGENT_TOKEN` | yes | An agent token (`RDS_AGENT_TOKENS` on the API; `agent` in `tokens.json` for `RDS_STORE=local` — [docs/agents.md](https://github.com/deven-bryant/rolling-design-sync/blob/main/docs/agents.md#2-get-the-agent-token-once) shows how to copy it out). |
|
|
133
|
+
| `RDS_FILE_KEY` | no | Default `fileKey`, so single-file users needn't pass it on every call. |
|
|
134
|
+
| `RDS_MCP_DEFAULT_LIMIT` | no | Page size when a listing call omits `limit` (default 25); not applied to `format=outline`, which comes whole. |
|
|
135
|
+
| `RDS_MCP_MAX_RESULT_CHARS` | no | Tool-result size budget (default 50,000); larger results come back as smaller pages (an outline as fewer whole lines, via `limit`, with its `X-RDS-Next-Cursor` as the cursor). |
|
|
136
|
+
|
|
137
|
+
The server exits with a message naming the missing variable(s) if a required
|
|
138
|
+
one is unset, and with a message naming `RDS_API_BASE_URL` if the API can't be
|
|
139
|
+
reached at startup (it needs the API running to know its tools).
|
|
140
|
+
|
|
141
|
+
## Install
|
|
142
|
+
|
|
143
|
+
New to Rolling Design Sync? The [quickstart](https://github.com/deven-bryant/rolling-design-sync/blob/main/docs/quickstart.md) runs the
|
|
144
|
+
API, the Figma plugin and this server end to end.
|
|
145
|
+
|
|
146
|
+
From npm (Node 20+): `npx @rolling-design-sync/mcp` (binary `rds-mcp`). Or
|
|
147
|
+
from a checkout of the repository:
|
|
148
|
+
|
|
149
|
+
```bash
|
|
150
|
+
npm install
|
|
151
|
+
```
|
|
152
|
+
|
|
153
|
+
The server entry point is then `apps/mcp/bin/rds-mcp.js`. Setup for **Claude Code, Cursor and Devin** — with the CLI
|
|
154
|
+
getting the same variables, and the agent token copied out of Docker — is in
|
|
155
|
+
[docs/agents.md](https://github.com/deven-bryant/rolling-design-sync/blob/main/docs/agents.md), along with the recipes. For other clients, replace `/path/to/rolling-design-sync`
|
|
156
|
+
with the absolute path of your checkout and fill in the env values. The token is
|
|
157
|
+
a secret — keep these configs out of version control (use your client's
|
|
158
|
+
user-level config).
|
|
159
|
+
|
|
160
|
+
### Windsurf
|
|
161
|
+
|
|
162
|
+
`~/.codeium/windsurf/mcp_config.json`:
|
|
163
|
+
|
|
164
|
+
```json
|
|
165
|
+
{
|
|
166
|
+
"mcpServers": {
|
|
167
|
+
"rds": {
|
|
168
|
+
"command": "node",
|
|
169
|
+
"args": ["/path/to/rolling-design-sync/apps/mcp/bin/rds-mcp.js"],
|
|
170
|
+
"env": {
|
|
171
|
+
"RDS_API_BASE_URL": "http://127.0.0.1:8787",
|
|
172
|
+
"RDS_AGENT_TOKEN": "<agent-token>",
|
|
173
|
+
"RDS_FILE_KEY": "<fileKey>"
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
```
|
|
179
|
+
|
|
180
|
+
### Other clients
|
|
181
|
+
|
|
182
|
+
Any client that launches stdio servers works: run
|
|
183
|
+
`node /path/to/rolling-design-sync/apps/mcp/bin/rds-mcp.js` with the env above.
|
|
184
|
+
|
|
185
|
+
## Local API note
|
|
186
|
+
|
|
187
|
+
With `RDS_STORE=local` or `memory`, the API only accepts a loopback `Host`
|
|
188
|
+
(`localhost`, `127.0.0.1`, `[::1]`, any port) and rejects browser `Origin`s.
|
|
189
|
+
Point `RDS_API_BASE_URL` at `http://localhost:<PORT>` or
|
|
190
|
+
`http://127.0.0.1:<PORT>` with the port the API is published on.
|
|
191
|
+
|
|
192
|
+
## Development
|
|
193
|
+
|
|
194
|
+
```bash
|
|
195
|
+
npm test -w @rolling-design-sync/mcp # DB-free: memory-store API on a loopback port + in-memory / stdio MCP clients
|
|
196
|
+
npm run build -w @rolling-design-sync/mcp
|
|
197
|
+
```
|
|
198
|
+
|
|
199
|
+
## License
|
|
200
|
+
|
|
201
|
+
[Apache-2.0](LICENSE), like the rest of the repository except `apps/api`
|
|
202
|
+
(FSL-1.1-ALv2).
|
package/bin/rds-mcp.js
ADDED
package/package.json
CHANGED
|
@@ -1,6 +1,53 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@rolling-design-sync/mcp",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"description": "
|
|
6
|
-
|
|
3
|
+
"version": "0.13.1",
|
|
4
|
+
"license": "Apache-2.0",
|
|
5
|
+
"description": "Local (stdio) MCP server for rolling-design-sync: its tools are generated at startup from the API's /v3/openapi.json (one per x-rds-mcp operation).",
|
|
6
|
+
"keywords": [
|
|
7
|
+
"figma",
|
|
8
|
+
"design-sync",
|
|
9
|
+
"mcp",
|
|
10
|
+
"model-context-protocol",
|
|
11
|
+
"agent",
|
|
12
|
+
"design-to-code"
|
|
13
|
+
],
|
|
14
|
+
"homepage": "https://github.com/deven-bryant/rolling-design-sync/tree/main/apps/mcp#readme",
|
|
15
|
+
"bugs": {
|
|
16
|
+
"url": "https://github.com/deven-bryant/rolling-design-sync/issues"
|
|
17
|
+
},
|
|
18
|
+
"repository": {
|
|
19
|
+
"type": "git",
|
|
20
|
+
"url": "git+https://github.com/deven-bryant/rolling-design-sync.git",
|
|
21
|
+
"directory": "apps/mcp"
|
|
22
|
+
},
|
|
23
|
+
"main": "src/server.js",
|
|
24
|
+
"bin": {
|
|
25
|
+
"rds-mcp": "bin/rds-mcp.js"
|
|
26
|
+
},
|
|
27
|
+
"files": [
|
|
28
|
+
"bin/",
|
|
29
|
+
"src/",
|
|
30
|
+
"README.md",
|
|
31
|
+
"LICENSE"
|
|
32
|
+
],
|
|
33
|
+
"scripts": {
|
|
34
|
+
"start": "node bin/rds-mcp.js",
|
|
35
|
+
"test": "node --test tests/env-fallback.test.js tests/mcp.test.js",
|
|
36
|
+
"build": "node --check bin/rds-mcp.js && node --check src/server.js && node --check src/config.js && node --check src/client.js && node --check src/tools.js"
|
|
37
|
+
},
|
|
38
|
+
"dependencies": {
|
|
39
|
+
"@modelcontextprotocol/sdk": "1.32.0",
|
|
40
|
+
"@rolling-design-sync/core": "^0.13.1",
|
|
41
|
+
"zod": "4.6.5"
|
|
42
|
+
},
|
|
43
|
+
"devDependencies": {
|
|
44
|
+
"@rolling-design-sync/api": "*"
|
|
45
|
+
},
|
|
46
|
+
"engines": {
|
|
47
|
+
"node": ">=20"
|
|
48
|
+
},
|
|
49
|
+
"publishConfig": {
|
|
50
|
+
"access": "public",
|
|
51
|
+
"provenance": true
|
|
52
|
+
}
|
|
53
|
+
}
|
package/src/client.js
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Minimal HTTP client for the v3 API. `request` resolves to
|
|
5
|
+
* `{ ok, status, contentType, data, nextCursor, retryAfter, method, path }` for any HTTP response
|
|
6
|
+
* (`application/json` and `+json` bodies parsed, others — ndjson included — as text;
|
|
7
|
+
* `nextCursor` from the X-RDS-Next-Cursor header and `retryAfter` from Retry-After, else null);
|
|
8
|
+
* network failures reject. Every request
|
|
9
|
+
* carries the agent token and `X-RDS-Client: <clientName>`.
|
|
10
|
+
*/
|
|
11
|
+
/**
|
|
12
|
+
* @typedef {{ ok: boolean, status: number, contentType: string, data: any, nextCursor: string | null,
|
|
13
|
+
* retryAfter: string | null, method: string, path: string }} ApiResponse
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
const JSON_TYPE = /^\s*application\/(?:[\w.-]+\+)?json\s*(?:;|$)/i;
|
|
17
|
+
|
|
18
|
+
function createApiClient({ baseUrl, token, clientName, fetchImpl = globalThis.fetch }) {
|
|
19
|
+
/**
|
|
20
|
+
* @param {string} method
|
|
21
|
+
* @param {string} path
|
|
22
|
+
* @param {{ query?: Record<string, any>, body?: unknown, signal?: AbortSignal }} [options]
|
|
23
|
+
* @returns {Promise<ApiResponse>}
|
|
24
|
+
*/
|
|
25
|
+
async function request(method, path, { query, body, signal } = {}) {
|
|
26
|
+
const url = new URL(baseUrl + path);
|
|
27
|
+
for (const [k, v] of Object.entries(query || {})) url.searchParams.set(k, v);
|
|
28
|
+
/** @type {Record<string, string>} */
|
|
29
|
+
const headers = { authorization: `Bearer ${token}`, accept: 'application/json', 'x-rds-client': clientName };
|
|
30
|
+
/** @type {RequestInit} */
|
|
31
|
+
const init = { method, headers };
|
|
32
|
+
if (signal) init.signal = signal;
|
|
33
|
+
if (body !== undefined) {
|
|
34
|
+
headers['content-type'] = 'application/json';
|
|
35
|
+
init.body = JSON.stringify(body);
|
|
36
|
+
}
|
|
37
|
+
const res = await fetchImpl(url.toString(), init);
|
|
38
|
+
const contentType = res.headers.get('content-type') || '';
|
|
39
|
+
const text = await res.text();
|
|
40
|
+
/** @type {any} */
|
|
41
|
+
let data = text;
|
|
42
|
+
if (JSON_TYPE.test(contentType) && text) {
|
|
43
|
+
try { data = JSON.parse(text); } catch (_) { data = text; }
|
|
44
|
+
}
|
|
45
|
+
const nextCursor = res.headers.get('x-rds-next-cursor') || null;
|
|
46
|
+
const retryAfter = res.headers.get('retry-after') || null;
|
|
47
|
+
return { ok: res.ok, status: res.status, contentType, data, nextCursor, retryAfter, method, path };
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
return { request };
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
module.exports = { createApiClient };
|
package/src/config.js
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
class ConfigError extends Error {}
|
|
4
|
+
|
|
5
|
+
const warnedVars = new Set();
|
|
6
|
+
const LEGACY_VAR = /^FDS_([A-Z0-9_]+)$/;
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Warns once per variable (per `warned` set) for each non-empty pre-0.10
|
|
10
|
+
* `FDS_<name>` in `env`, naming its `RDS_<name>` replacement. Their values are
|
|
11
|
+
* never read.
|
|
12
|
+
*/
|
|
13
|
+
function warnLegacyEnv(env, { warn = message => process.stderr.write(`${message}\n`), warned = warnedVars } = {}) {
|
|
14
|
+
for (const key of Object.keys(env).sort()) {
|
|
15
|
+
const m = LEGACY_VAR.exec(key);
|
|
16
|
+
if (!m || !env[key] || warned.has(key)) continue;
|
|
17
|
+
warned.add(key);
|
|
18
|
+
warn(`rds-mcp: ${key} is no longer read; set RDS_${m[1]} instead`);
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** `RDS_<name>` from `env`; empty counts as unset. */
|
|
23
|
+
const envVar = (env, name) => env[`RDS_${name}`] || undefined;
|
|
24
|
+
|
|
25
|
+
const DEFAULT_LIMIT = 25;
|
|
26
|
+
const MAX_RESULT_CHARS = 50000;
|
|
27
|
+
|
|
28
|
+
/** A positive integer from env var `name` (`RDS_` + `name`), else `fallback`. */
|
|
29
|
+
function positiveInt(value, name, fallback) {
|
|
30
|
+
if (value === undefined || !String(value).trim()) return fallback;
|
|
31
|
+
const n = Number(String(value).trim());
|
|
32
|
+
if (!Number.isInteger(n) || n < 1) throw new ConfigError(`rds-mcp: RDS_${name} must be a positive integer, got "${value}".`);
|
|
33
|
+
return n;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* Reads the server config from env. `RDS_API_BASE_URL` and `RDS_AGENT_TOKEN`
|
|
38
|
+
* are required; `RDS_FILE_KEY` is an optional default for tools' `fileKey`;
|
|
39
|
+
* `RDS_MCP_DEFAULT_LIMIT` (25) is the page size when a listing call omits
|
|
40
|
+
* `limit`, and `RDS_MCP_MAX_RESULT_CHARS` (50,000) the tool-result size budget.
|
|
41
|
+
*/
|
|
42
|
+
function readConfig(env = process.env, envOptions = {}) {
|
|
43
|
+
warnLegacyEnv(env, envOptions);
|
|
44
|
+
const rds = name => envVar(env, name);
|
|
45
|
+
const baseUrl = String(rds('API_BASE_URL') || '').trim().replace(/\/+$/, '');
|
|
46
|
+
const token = String(rds('AGENT_TOKEN') || '').trim();
|
|
47
|
+
const defaultFileKey = String(rds('FILE_KEY') || '').trim() || null;
|
|
48
|
+
const defaultLimit = positiveInt(rds('MCP_DEFAULT_LIMIT'), 'MCP_DEFAULT_LIMIT', DEFAULT_LIMIT);
|
|
49
|
+
const maxResultChars = positiveInt(rds('MCP_MAX_RESULT_CHARS'), 'MCP_MAX_RESULT_CHARS', MAX_RESULT_CHARS);
|
|
50
|
+
const missing = [];
|
|
51
|
+
if (!baseUrl) missing.push('RDS_API_BASE_URL');
|
|
52
|
+
if (!token) missing.push('RDS_AGENT_TOKEN');
|
|
53
|
+
if (missing.length) {
|
|
54
|
+
throw new ConfigError(
|
|
55
|
+
`rds-mcp: missing required environment variable(s): ${missing.join(', ')}.\n` +
|
|
56
|
+
'Set RDS_API_BASE_URL to the rolling-design-sync API origin (e.g. http://127.0.0.1:8787) ' +
|
|
57
|
+
'and RDS_AGENT_TOKEN to an agent token, in the "env" block of your MCP client config.',
|
|
58
|
+
);
|
|
59
|
+
}
|
|
60
|
+
try {
|
|
61
|
+
const url = new URL(baseUrl);
|
|
62
|
+
if (url.protocol !== 'http:' && url.protocol !== 'https:') throw new Error('bad protocol');
|
|
63
|
+
} catch (_) {
|
|
64
|
+
throw new ConfigError(`rds-mcp: RDS_API_BASE_URL must be an http(s) URL, got "${baseUrl}".`);
|
|
65
|
+
}
|
|
66
|
+
return { baseUrl, token, defaultFileKey, defaultLimit, maxResultChars };
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
module.exports = { readConfig, envVar, warnLegacyEnv, ConfigError, DEFAULT_LIMIT, MAX_RESULT_CHARS };
|
package/src/server.js
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const { Server } = require('@modelcontextprotocol/sdk/server/index.js');
|
|
4
|
+
const { StdioServerTransport } = require('@modelcontextprotocol/sdk/server/stdio.js');
|
|
5
|
+
const { CallToolRequestSchema, ListToolsRequestSchema, McpError, ErrorCode } = require('@modelcontextprotocol/sdk/types.js');
|
|
6
|
+
const { readConfig, DEFAULT_LIMIT, MAX_RESULT_CHARS } = require('./config');
|
|
7
|
+
const { createApiClient } = require('./client');
|
|
8
|
+
const { toolsFromOpenApi, toRequest, ToolError } = require('./tools');
|
|
9
|
+
const pkg = require('../package.json');
|
|
10
|
+
|
|
11
|
+
const CLIENT = `mcp/${pkg.version}`;
|
|
12
|
+
const OPENAPI_PATH = '/v3/openapi.json';
|
|
13
|
+
const STARTUP_TIMEOUT_MS = 15000;
|
|
14
|
+
|
|
15
|
+
const INSTRUCTIONS = [
|
|
16
|
+
'rolling-design-sync tracks what changed in Figma since it was last built, node by node. The tools are generated from the connected API\'s OpenAPI document.',
|
|
17
|
+
'Loop: (1) list_nodes for the screen or component you are working on (or claim_nodes to lease nodes when several agents share a file; summarize / list_work_items for an overview);',
|
|
18
|
+
'(2) implement each node\'s `changes` — per property { built, now, category }, with token names where a value is bound — mapping it to code via Code Connect / figma.ts mappings where present, and pulling live details for that node only from the Figma MCP via its figmaUrl;',
|
|
19
|
+
'(3) clear_nodes with the nodeId + contentHash pairs you read and the commit SHA.',
|
|
20
|
+
'An item that comes back `stale` changed again after you read it: re-read that node with get_node, implement the newer change, and clear it with its new contentHash — never retry the old hash.',
|
|
21
|
+
'Use block_node for a node you cannot implement instead of clearing it.',
|
|
22
|
+
'Any tool that takes fileKey / nodeId also takes a Figma link as `url`; fileKey defaults to RDS_FILE_KEY when that is set in the server env.',
|
|
23
|
+
`Listing tools return ${DEFAULT_LIMIT} results per call unless you pass limit (text formats: up to that many lines; format=outline: the whole outline unless you pass limit, in lines); a result that ends with \`More results: call again with cursor="…"\` has more — repeat the call with that cursor and every other input unchanged. Results too large for one reply come back as a smaller page.`,
|
|
24
|
+
'Where the connected API offers them (they then appear in the tool inputs): expand=instances follows instances into their main components, so one list_nodes / summarize / list_work_items call covers everything a screen uses;',
|
|
25
|
+
'format=outline returns a screen as an indented text tree — the quickest answer to "what\'s in this screen" (with expand=instances for the components inside);',
|
|
26
|
+
'changes=names lists only the changed property names (changedProps) and changes=diff every built → now value — use list_work_items with expand=instances and changes=names for "what do I build", then get_node for the values of one node.',
|
|
27
|
+
].join(' ');
|
|
28
|
+
|
|
29
|
+
const TRUNCATED = 'result truncated — use fields= or get_node';
|
|
30
|
+
const moreResults = cursor => `More results: call again with cursor="${cursor}"`;
|
|
31
|
+
/** Characters an outline page keeps free for its X-RDS-Next-Cursor, beyond the one it came with. */
|
|
32
|
+
const CURSOR_ROOM = 64;
|
|
33
|
+
|
|
34
|
+
class StartupError extends Error {}
|
|
35
|
+
|
|
36
|
+
const text = (value, isError = false) => ({
|
|
37
|
+
content: [{ type: 'text', text: typeof value === 'string' ? value : JSON.stringify(value, null, 2) }],
|
|
38
|
+
...(isError ? { isError: true } : {}),
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
/** A non-2xx response for the model: the problem's title, detail and hint, else the body as-is. */
|
|
42
|
+
/** Seconds until a `Retry-After` value (delta-seconds or an HTTP date); null when absent or unreadable. */
|
|
43
|
+
function retrySeconds(value, now = Date.now()) {
|
|
44
|
+
if (value === null || value === undefined || value === '') return null;
|
|
45
|
+
const text = String(value).trim();
|
|
46
|
+
if (/^\d+$/.test(text)) return Number(text);
|
|
47
|
+
const at = Date.parse(text);
|
|
48
|
+
return Number.isNaN(at) ? null : Math.max(0, Math.ceil((at - now) / 1000));
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** A 429: the retry time (Retry-After, else the problem's `retryAfter`) first, then the API's detail. */
|
|
52
|
+
function rateLimited({ data, retryAfter, method, path }) {
|
|
53
|
+
const problem = data && typeof data === 'object' ? data : {};
|
|
54
|
+
const seconds = retrySeconds(retryAfter) ?? retrySeconds(problem.retryAfter);
|
|
55
|
+
const when = seconds === null ? 'retry later' : `retry in ${seconds} s`;
|
|
56
|
+
const detail = problem.detail || (typeof data === 'string' ? data.trim() : '');
|
|
57
|
+
const lines = [`HTTP 429 ${method} ${path} — rate limited (rate_limited): ${when}.${detail ? ` ${detail}` : ''}`];
|
|
58
|
+
if (problem.hint) lines.push(`Hint: ${problem.hint}`);
|
|
59
|
+
return text(lines.join('\n'), true);
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function httpError({ status, data, method, path, retryAfter }) {
|
|
63
|
+
if (status === 429) return rateLimited({ data, retryAfter, method, path });
|
|
64
|
+
const head = `HTTP ${status} ${method} ${path}`;
|
|
65
|
+
if (data && typeof data === 'object' && (data.title || data.detail)) {
|
|
66
|
+
const lines = [`${head} — ${data.title || 'Error'}${data.code ? ` (${data.code})` : ''}: ${data.detail || ''}`.trim()];
|
|
67
|
+
if (data.hint) lines.push(`Hint: ${data.hint}`);
|
|
68
|
+
if (Array.isArray(data.validParameters) && data.validParameters.length) lines.push(`Valid parameters: ${data.validParameters.join(', ')}`);
|
|
69
|
+
return text(lines.join('\n'), true);
|
|
70
|
+
}
|
|
71
|
+
const body = data && typeof data === 'object' ? JSON.stringify(data) : String(data || '').trim();
|
|
72
|
+
return text(body ? `${head} — ${body}` : head, true);
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
const reason = err => (err && err.cause && err.cause.message) || (err && err.message) || String(err);
|
|
76
|
+
|
|
77
|
+
/** The OpenAPI document at `${baseUrl}/v3/openapi.json`; a StartupError naming RDS_API_BASE_URL when it can't be had. */
|
|
78
|
+
async function fetchOpenApi(api, baseUrl) {
|
|
79
|
+
const where = `${baseUrl}${OPENAPI_PATH}`;
|
|
80
|
+
const fix = 'Start the API, or set RDS_API_BASE_URL to the origin of a running rolling-design-sync API (v3), e.g. http://127.0.0.1:8787.';
|
|
81
|
+
let res;
|
|
82
|
+
try {
|
|
83
|
+
res = await api.request('GET', OPENAPI_PATH, { signal: AbortSignal.timeout(STARTUP_TIMEOUT_MS) });
|
|
84
|
+
} catch (err) {
|
|
85
|
+
throw new StartupError(`rds-mcp: could not reach the rolling-design-sync API at RDS_API_BASE_URL=${baseUrl} to load its tools from ${where}: ${reason(err)}. ${fix}`);
|
|
86
|
+
}
|
|
87
|
+
if (!res.ok) throw new StartupError(`rds-mcp: GET ${where} returned HTTP ${res.status}; RDS_API_BASE_URL=${baseUrl} does not look like a rolling-design-sync API with v3. ${fix}`);
|
|
88
|
+
if (!res.data || typeof res.data !== 'object' || !res.data.paths) {
|
|
89
|
+
throw new StartupError(`rds-mcp: ${where} is not an OpenAPI document; RDS_API_BASE_URL=${baseUrl} does not look like a rolling-design-sync API with v3. ${fix}`);
|
|
90
|
+
}
|
|
91
|
+
return res.data;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* The MCP server for `config`, with one tool per `x-rds-mcp` operation of the
|
|
96
|
+
* API's OpenAPI document (fetched now unless `doc` is given). Rejects with a
|
|
97
|
+
* StartupError when the document can't be loaded or has no agent operations.
|
|
98
|
+
*
|
|
99
|
+
* Listing tools get `limit` = `config.defaultLimit` when the call omits it. A
|
|
100
|
+
* JSON result is sent pretty-printed, ending with a "More results" line when it
|
|
101
|
+
* has `nextCursor`; one longer than `config.maxResultChars` is re-requested
|
|
102
|
+
* with `limit` halved (down to 1), then cut with a note. Text formats (ndjson,
|
|
103
|
+
* md, …) are sent as the API returned them. format=outline gets no default
|
|
104
|
+
* `limit`; it ends with a "More results" line when the response has an
|
|
105
|
+
* X-RDS-Next-Cursor header, and one too long is re-requested with `limit` = the
|
|
106
|
+
* whole lines that fit, so its cursor is the API's for exactly those lines.
|
|
107
|
+
*/
|
|
108
|
+
/**
|
|
109
|
+
* @param {any} config
|
|
110
|
+
* @param {{ fetchImpl?: typeof fetch, doc?: any }} [options]
|
|
111
|
+
*/
|
|
112
|
+
async function createServer(config, { fetchImpl, doc } = {}) {
|
|
113
|
+
const defaultLimit = config.defaultLimit || DEFAULT_LIMIT;
|
|
114
|
+
const maxResultChars = config.maxResultChars || MAX_RESULT_CHARS;
|
|
115
|
+
const api = createApiClient({ baseUrl: config.baseUrl, token: config.token, clientName: CLIENT, fetchImpl });
|
|
116
|
+
const openapi = doc || await fetchOpenApi(api, config.baseUrl);
|
|
117
|
+
const tools = toolsFromOpenApi(openapi);
|
|
118
|
+
if (!tools.length) {
|
|
119
|
+
throw new StartupError(`rds-mcp: ${config.baseUrl}${OPENAPI_PATH} lists no agent operations (x-rds-mcp), so there are no tools to serve. Check that RDS_API_BASE_URL points at a rolling-design-sync API with v3.`);
|
|
120
|
+
}
|
|
121
|
+
const byName = new Map(tools.map(t => [t.name, t]));
|
|
122
|
+
|
|
123
|
+
const server = new Server({ name: 'rds-mcp', version: pkg.version }, { capabilities: { tools: {} }, instructions: INSTRUCTIONS });
|
|
124
|
+
|
|
125
|
+
server.setRequestHandler(ListToolsRequestSchema, () => ({
|
|
126
|
+
tools: tools.map(({ name, title, description, inputSchema, annotations }) => ({ name, title, description, inputSchema, annotations })),
|
|
127
|
+
}));
|
|
128
|
+
|
|
129
|
+
server.setRequestHandler(CallToolRequestSchema, async request => {
|
|
130
|
+
const tool = byName.get(request.params.name);
|
|
131
|
+
if (!tool) throw new McpError(ErrorCode.InvalidParams, `Tool ${request.params.name} not found`);
|
|
132
|
+
let req;
|
|
133
|
+
try {
|
|
134
|
+
req = toRequest(tool, request.params.arguments, { defaultFileKey: config.defaultFileKey });
|
|
135
|
+
} catch (err) {
|
|
136
|
+
if (err instanceof ToolError) return text(err.message, true);
|
|
137
|
+
throw err;
|
|
138
|
+
}
|
|
139
|
+
const outline = req.query.format === 'outline';
|
|
140
|
+
let limit = null;
|
|
141
|
+
if (tool.paged) {
|
|
142
|
+
if (req.query.limit === undefined) {
|
|
143
|
+
if (!outline) {
|
|
144
|
+
limit = tool.paged.maxLimit ? Math.min(defaultLimit, tool.paged.maxLimit) : defaultLimit;
|
|
145
|
+
req.query.limit = String(limit);
|
|
146
|
+
}
|
|
147
|
+
} else {
|
|
148
|
+
limit = Number(req.query.limit);
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
for (;;) {
|
|
152
|
+
let res;
|
|
153
|
+
try {
|
|
154
|
+
res = await api.request(req.method, req.path, { query: req.query, body: req.body });
|
|
155
|
+
} catch (err) {
|
|
156
|
+
return text(`Could not reach the rolling-design-sync API at ${config.baseUrl} (RDS_API_BASE_URL): ${reason(err)}`, true);
|
|
157
|
+
}
|
|
158
|
+
if (!res.ok) return httpError(res);
|
|
159
|
+
if (res.data === '' || res.data === null) return text(`HTTP ${res.status} ${req.method} ${req.path}: no content.`);
|
|
160
|
+
if (typeof res.data === 'string' && outline) {
|
|
161
|
+
const paging = res.nextCursor ? `${res.data.endsWith('\n') ? '\n' : '\n\n'}${moreResults(res.nextCursor)}` : '';
|
|
162
|
+
if (res.data.length + paging.length <= maxResultChars) return text(res.data + paging);
|
|
163
|
+
const lines = res.data.replace(/\n$/, '').split('\n');
|
|
164
|
+
const room = maxResultChars - `\n${moreResults(res.nextCursor || '')}`.length - CURSOR_ROOM;
|
|
165
|
+
let kept = 0;
|
|
166
|
+
for (let size = 0; kept < lines.length && size + lines[kept].length + 1 <= room; kept++) size += lines[kept].length + 1;
|
|
167
|
+
const fewer = Math.max(1, Math.min(kept, lines.length - 1));
|
|
168
|
+
if (lines.length > 1 && limit !== 1) {
|
|
169
|
+
limit = fewer;
|
|
170
|
+
req.query.limit = String(limit);
|
|
171
|
+
continue;
|
|
172
|
+
}
|
|
173
|
+
const note = `\n\n${TRUNCATED}`;
|
|
174
|
+
const tail = res.nextCursor ? `\n\n${moreResults(res.nextCursor)}` : '';
|
|
175
|
+
return text(res.data.slice(0, Math.max(0, maxResultChars - note.length - tail.length)) + note + tail);
|
|
176
|
+
}
|
|
177
|
+
if (typeof res.data === 'string') return text(res.data);
|
|
178
|
+
const body = JSON.stringify(res.data, null, 2);
|
|
179
|
+
const cursor = res.data && typeof res.data.nextCursor === 'string' && res.data.nextCursor ? res.data.nextCursor : null;
|
|
180
|
+
const paging = cursor ? `\n\n${moreResults(cursor)}` : '';
|
|
181
|
+
if (body.length + paging.length <= maxResultChars) return text(body + paging);
|
|
182
|
+
if (Number.isInteger(limit) && limit > 1) {
|
|
183
|
+
limit = Math.max(1, Math.floor(limit / 2));
|
|
184
|
+
req.query.limit = String(limit);
|
|
185
|
+
continue;
|
|
186
|
+
}
|
|
187
|
+
const note = `\n\n${TRUNCATED}`;
|
|
188
|
+
return text(body.slice(0, Math.max(0, maxResultChars - note.length - paging.length)) + note + paging);
|
|
189
|
+
}
|
|
190
|
+
});
|
|
191
|
+
|
|
192
|
+
return server;
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
async function main({ env = process.env } = {}) {
|
|
196
|
+
const server = await createServer(readConfig(env));
|
|
197
|
+
await server.connect(new StdioServerTransport());
|
|
198
|
+
return server;
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
module.exports = { createServer, httpError, retrySeconds, main, fetchOpenApi, StartupError, INSTRUCTIONS, CLIENT, TRUNCATED, moreResults };
|
package/src/tools.js
ADDED
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/*
|
|
4
|
+
* MCP tools from the API's OpenAPI document (docs/api-v3-phase2.md, "8.
|
|
5
|
+
* Generated MCP tools"): one tool per operation annotated `x-rds-mcp`, whose
|
|
6
|
+
* input schema is the operation's path, query and body parameters, with the
|
|
7
|
+
* JSON Schemas passed through as-is.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
const { parseFigmaUrl } = require('@rolling-design-sync/core');
|
|
11
|
+
|
|
12
|
+
const METHODS = ['get', 'post', 'put', 'patch', 'delete'];
|
|
13
|
+
/** Path parameters a `url` (Figma link) query parameter can supply, as `-`. */
|
|
14
|
+
const URL_PARAMS = ['fileKey', 'nodeId'];
|
|
15
|
+
const PLACEHOLDER = '-';
|
|
16
|
+
/** Input keys holding node ids; a Figma link with a node-id is accepted there too. */
|
|
17
|
+
const NODE_KEYS = new Set(['nodeId', 'under', 'nodeIds']);
|
|
18
|
+
|
|
19
|
+
class ToolError extends Error {}
|
|
20
|
+
|
|
21
|
+
const describe = (schema, description) => (description && !schema.description ? { ...schema, description } : schema);
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Every `x-rds-mcp` operation of `doc` as a tool:
|
|
25
|
+
* `{ name, title, description, inputSchema, annotations, method, path, params, bodyProps, bodyKey, bodyRequired, paged }`.
|
|
26
|
+
* `params` maps an input name to `path` or `query`; body inputs are the body
|
|
27
|
+
* schema's properties (`bodyProps`), or the whole body under `bodyKey` when
|
|
28
|
+
* they are not an object's properties or collide with a parameter name.
|
|
29
|
+
* `paged` is `{ maxLimit }` for a read-only operation with a `limit` query
|
|
30
|
+
* parameter (a listing the server may page), else null.
|
|
31
|
+
*/
|
|
32
|
+
function toolsFromOpenApi(doc) {
|
|
33
|
+
const tools = [];
|
|
34
|
+
const seen = new Set();
|
|
35
|
+
for (const [path, item] of Object.entries((doc && doc.paths) || {})) {
|
|
36
|
+
for (const method of METHODS) {
|
|
37
|
+
const op = item && item[method];
|
|
38
|
+
const name = op && op['x-rds-mcp'] && op['x-rds-mcp'].tool;
|
|
39
|
+
if (typeof name !== 'string' || !name || seen.has(name)) continue;
|
|
40
|
+
seen.add(name);
|
|
41
|
+
tools.push(toolFromOperation(name, method.toUpperCase(), path, op, item.parameters || []));
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
return tools;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function toolFromOperation(name, method, path, op, shared) {
|
|
48
|
+
const byKey = new Map();
|
|
49
|
+
for (const p of [...shared, ...(op.parameters || [])]) {
|
|
50
|
+
if (p && (p.in === 'path' || p.in === 'query')) byKey.set(`${p.in}:${p.name}`, p);
|
|
51
|
+
}
|
|
52
|
+
const parameters = [...byKey.values()];
|
|
53
|
+
const properties = {};
|
|
54
|
+
const required = [];
|
|
55
|
+
const params = {};
|
|
56
|
+
const takesUrl = parameters.some(p => p.in === 'query' && p.name === 'url');
|
|
57
|
+
for (const p of parameters) {
|
|
58
|
+
properties[p.name] = describe(p.schema || {}, p.description);
|
|
59
|
+
params[p.name] = p.in;
|
|
60
|
+
const suppliedByUrl = p.in === 'path' && takesUrl && URL_PARAMS.includes(p.name);
|
|
61
|
+
if ((p.required || p.in === 'path') && !suppliedByUrl) required.push(p.name);
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
let bodyProps = null;
|
|
65
|
+
let bodyKey = null;
|
|
66
|
+
let bodyRequired = false;
|
|
67
|
+
const content = op.requestBody && op.requestBody.content;
|
|
68
|
+
const schema = content && content['application/json'] && content['application/json'].schema;
|
|
69
|
+
if (schema) {
|
|
70
|
+
bodyRequired = !!op.requestBody.required;
|
|
71
|
+
const props = schema.properties;
|
|
72
|
+
const types = [].concat(schema.type || []);
|
|
73
|
+
if (props && types.includes('object') && !Object.keys(props).some(k => k in properties)) {
|
|
74
|
+
bodyProps = Object.keys(props);
|
|
75
|
+
Object.assign(properties, props);
|
|
76
|
+
required.push(...(schema.required || []));
|
|
77
|
+
} else {
|
|
78
|
+
bodyKey = 'body';
|
|
79
|
+
properties.body = describe(schema, op.requestBody.description || 'The request body.');
|
|
80
|
+
if (bodyRequired) required.push('body');
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
const readOnly = method === 'GET';
|
|
85
|
+
const limitParam = readOnly && parameters.find(p => p.in === 'query' && p.name === 'limit');
|
|
86
|
+
const paged = limitParam ? { maxLimit: Number.isInteger((limitParam.schema || {}).maximum) ? limitParam.schema.maximum : null } : null;
|
|
87
|
+
return {
|
|
88
|
+
name,
|
|
89
|
+
title: op.summary || name,
|
|
90
|
+
description: [op.summary, op.description].filter(Boolean).join('\n\n') || name,
|
|
91
|
+
inputSchema: { type: 'object', properties, ...(required.length ? { required: [...new Set(required)] } : {}), additionalProperties: false },
|
|
92
|
+
annotations: {
|
|
93
|
+
...(op.summary ? { title: op.summary } : {}),
|
|
94
|
+
readOnlyHint: readOnly,
|
|
95
|
+
...(readOnly ? {} : { destructiveHint: false }),
|
|
96
|
+
openWorldHint: false,
|
|
97
|
+
},
|
|
98
|
+
method,
|
|
99
|
+
path,
|
|
100
|
+
params,
|
|
101
|
+
bodyProps,
|
|
102
|
+
bodyKey,
|
|
103
|
+
bodyRequired,
|
|
104
|
+
paged,
|
|
105
|
+
};
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
const looksLikeUrl = v => typeof v === 'string' && (/^[a-z][a-z0-9+.-]*:\/\//i.test(v.trim()) || /figma\.com\//i.test(v));
|
|
109
|
+
const present = v => v !== undefined && v !== null && !(typeof v === 'string' && !v.trim());
|
|
110
|
+
|
|
111
|
+
/** `value` with every Figma link under a node-id key replaced by its node id; the links' file keys go to `fileKeys`. */
|
|
112
|
+
function unlinkNodes(value, key, where, fileKeys) {
|
|
113
|
+
if (Array.isArray(value)) return value.map((v, i) => unlinkNodes(v, key, `${where}[${i}]`, fileKeys));
|
|
114
|
+
if (value && typeof value === 'object') {
|
|
115
|
+
return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, unlinkNodes(v, k, `${where}.${k}`, fileKeys)]));
|
|
116
|
+
}
|
|
117
|
+
if (!NODE_KEYS.has(key) || !looksLikeUrl(value)) return value;
|
|
118
|
+
const parsed = parseFigmaUrl(value.trim());
|
|
119
|
+
if (!parsed || !parsed.nodeId) throw new ToolError(`${where}: '${value}' is not a Figma link with a node-id (…?node-id=1-2).`);
|
|
120
|
+
fileKeys.add(parsed.fileKey);
|
|
121
|
+
return parsed.nodeId;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
const queryValue = v => (Array.isArray(v) ? v.join(',') : v !== null && typeof v === 'object' ? JSON.stringify(v) : String(v));
|
|
125
|
+
|
|
126
|
+
/**
|
|
127
|
+
* The HTTP request `{ method, path, query, body }` for a call of `tool` with
|
|
128
|
+
* `args`. A `url` supplies `fileKey` / `nodeId` (as `-`); without either,
|
|
129
|
+
* `fileKey` comes from node links in the inputs, then `defaultFileKey`.
|
|
130
|
+
*/
|
|
131
|
+
function toRequest(tool, args, { defaultFileKey = null } = {}) {
|
|
132
|
+
const input = args && typeof args === 'object' ? args : {};
|
|
133
|
+
const unknown = Object.keys(input).filter(k => !(k in tool.inputSchema.properties));
|
|
134
|
+
if (unknown.length) {
|
|
135
|
+
throw new ToolError(`${tool.name}: unknown input(s) ${unknown.join(', ')}. Valid inputs: ${Object.keys(tool.inputSchema.properties).join(', ')}.`);
|
|
136
|
+
}
|
|
137
|
+
const fileKeys = new Set();
|
|
138
|
+
const values = {};
|
|
139
|
+
for (const [k, v] of Object.entries(input)) if (present(v)) values[k] = unlinkNodes(typeof v === 'string' ? v.trim() : v, k, k, fileKeys);
|
|
140
|
+
|
|
141
|
+
const url = tool.params.url === 'query' ? values.url : undefined;
|
|
142
|
+
const pathValues = {};
|
|
143
|
+
for (const name of Object.keys(tool.params).filter(n => tool.params[n] === 'path')) {
|
|
144
|
+
let v = values[name];
|
|
145
|
+
if (v === undefined && url !== undefined && URL_PARAMS.includes(name)) v = PLACEHOLDER;
|
|
146
|
+
if (v === undefined && name === 'fileKey') v = fileKeys.size === 1 ? [...fileKeys][0] : defaultFileKey || undefined;
|
|
147
|
+
if (v === undefined) {
|
|
148
|
+
if (name === 'fileKey') {
|
|
149
|
+
throw new ToolError('fileKey is required: pass it (or a Figma link as url), or set RDS_FILE_KEY in the MCP server env. It is the <fileKey> segment of figma.com/design/<fileKey>/….');
|
|
150
|
+
}
|
|
151
|
+
throw new ToolError(`${name} is required${URL_PARAMS.includes(name) && tool.params.url ? ': pass it, or a Figma link with a node-id as url' : ''}.`);
|
|
152
|
+
}
|
|
153
|
+
pathValues[name] = String(v);
|
|
154
|
+
}
|
|
155
|
+
if (pathValues.fileKey !== undefined) {
|
|
156
|
+
const target = pathValues.fileKey === PLACEHOLDER ? (parseFigmaUrl(url) || {}).fileKey : pathValues.fileKey;
|
|
157
|
+
const other = target && [...fileKeys].find(k => k !== target);
|
|
158
|
+
if (other) throw new ToolError(`A link names file '${other}', but the call is for file '${target}'. Address each file in its own call.`);
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
const path = tool.path.replace(/\{([^}]+)\}/g, (_, k) => encodeURIComponent(pathValues[k]));
|
|
162
|
+
const query = {};
|
|
163
|
+
for (const [k, where] of Object.entries(tool.params)) if (where === 'query' && values[k] !== undefined) query[k] = queryValue(values[k]);
|
|
164
|
+
|
|
165
|
+
let body;
|
|
166
|
+
if (tool.bodyProps) {
|
|
167
|
+
const picked = Object.fromEntries(tool.bodyProps.filter(k => values[k] !== undefined).map(k => [k, values[k]]));
|
|
168
|
+
if (Object.keys(picked).length || tool.bodyRequired) body = picked;
|
|
169
|
+
} else if (tool.bodyKey) {
|
|
170
|
+
body = values[tool.bodyKey];
|
|
171
|
+
if (body === undefined && tool.bodyRequired) body = {};
|
|
172
|
+
}
|
|
173
|
+
return { method: tool.method, path, query, body };
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
module.exports = { toolsFromOpenApi, toRequest, ToolError, URL_PARAMS };
|