@abgov/adsp-sdk-mcp-server 1.23.0 → 1.24.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/README.md +50 -5
- package/assets/docs/services/access-service.md +10 -12
- package/assets/docs/services/audit-service.md +252 -133
- package/assets/docs/services/configuration-service.md +163 -59
- package/assets/docs/services/event-service.md +138 -33
- package/assets/docs/services/form-service.md +152 -12
- package/assets/docs/services/notification-service.md +2 -0
- package/assets/docs/services/pdf-service.md +7 -7
- package/assets/docs/services/project-planner-service.md +11 -11
- package/assets/docs/services/status-service.md +162 -6
- package/assets/docs/services/token-handler.md +68 -10
- package/assets/docs/services/value-service.md +95 -9
- package/assets/docs/tutorials/form-service/building-forms.md +1 -1
- package/assets/docs/tutorials/form-service/cheat-sheet.md +1 -1
- package/assets/docs/tutorials/form-service/form-app.md +1 -1
- package/assets/docs/tutorials/form-service/form-submissions.md +1 -1
- package/assets/docs/tutorials/form-service/introduction.md +1 -1
- package/assets/docs/tutorials/form-service/security.md +1 -1
- package/assets/docs/tutorials/status-service/health.md +1 -1
- package/assets/docs/tutorials/status-service/status.md +2 -2
- package/package.json +2 -1
- package/src/config.d.ts +11 -0
- package/src/config.js +47 -0
- package/src/config.js.map +1 -0
- package/src/guards.d.ts +11 -0
- package/src/guards.js +94 -0
- package/src/guards.js.map +1 -0
- package/src/http.d.ts +17 -1
- package/src/http.js +23 -17
- package/src/http.js.map +1 -1
- package/src/main.js +8 -4
- package/src/main.js.map +1 -1
- package/src/semaphore.d.ts +16 -0
- package/src/semaphore.js +71 -0
- package/src/semaphore.js.map +1 -0
- package/src/server.js +10 -3
- package/src/server.js.map +1 -1
- package/src/tools/liveToolLimit.d.ts +8 -0
- package/src/tools/liveToolLimit.js +45 -0
- package/src/tools/liveToolLimit.js.map +1 -0
- package/src/tools/registerConfigurationSchemaTool.js +3 -2
- package/src/tools/registerConfigurationSchemaTool.js.map +1 -1
- package/src/tools/registerServiceRolesTool.js +3 -2
- package/src/tools/registerServiceRolesTool.js.map +1 -1
- package/src/tools/types.d.ts +6 -2
|
@@ -6,7 +6,7 @@ parent: Services
|
|
|
6
6
|
|
|
7
7
|
# Value service
|
|
8
8
|
|
|
9
|
-
Value service provides an append only time series data store. It serves as the underlying store for the event log.
|
|
9
|
+
Value service provides an append only time series data store. It serves as the underlying store for the event log: [event service](event-service.md) writes every logged domain event as a record of a value.
|
|
10
10
|
|
|
11
11
|
## Client roles
|
|
12
12
|
|
|
@@ -20,11 +20,53 @@ client `urn:ads:platform:value-service`
|
|
|
20
20
|
|
|
21
21
|
The export service's `urn:ads:platform:export-service:export-job` role can also read values, so that export jobs can read the event log.
|
|
22
22
|
|
|
23
|
+
## Tenancy
|
|
24
|
+
|
|
25
|
+
Values, metrics and value definitions belong to a tenant. Every record is stored with the tenant it was written to, and reads only return records of the tenant they act on.
|
|
26
|
+
|
|
27
|
+
- **Which tenant is used.** Tenant users and service accounts always act on the tenant of their token. Core (platform) users act on the tenant set by the `tenantId` query parameter; writes also accept `tenantId` in the body. An invalid `tenantId` responds 400.
|
|
28
|
+
- **Writing values.** Tenant users write to their own tenant; setting a `tenantId` for another tenant responds 403. Core users must set a tenant, otherwise the write responds 400. Event service writes the event log this way, as a core service account.
|
|
29
|
+
- **Reading records.** `GET /value/v1/{namespace}/values/{name}` responds 400 for a tenant user without a tenant context. Core users with `value-reader` can leave out `tenantId` to read the records of all tenants.
|
|
30
|
+
- **Counts and metrics.** Counting records and reading metrics require a tenant context, so core users must set `tenantId`; without it the request responds 400.
|
|
31
|
+
- **Platform metrics.** `GET /value/v1/{namespace}/values/{name}/platform-metrics` is the only endpoint that combines tenants in one response. It needs a core user with `value-platform-metrics-reader`, and labels each interval with its tenant.
|
|
32
|
+
- **Latest values of a namespace.** `GET /value/v1/{namespace}/values` acts on the tenant of the caller's token. Core users reading a tenant should read each value with `tenantId` instead.
|
|
33
|
+
- **Platform versus tenant definitions.** Value definitions come from the tenant's configuration and from core (platform) configuration. When reading a single definition, a tenant definition takes precedence over a core definition with the same namespace and name. Tenants can't change core definitions through this API, and can't create a definition whose namespace and name are already used by a core definition (409).
|
|
34
|
+
- **Isolation.** Records of other tenants are never returned, and definitions of other tenants respond 404.
|
|
35
|
+
- **Role scope.** Roles are checked in the tenant being acted on. Core users with the same role are also allowed.
|
|
36
|
+
|
|
37
|
+
## API overview
|
|
38
|
+
|
|
39
|
+
All endpoints are under `https://value-service.adsp.alberta.ca/value/v1`. See the [API documentation](https://api.adsp.alberta.ca) for request and response schemas.
|
|
40
|
+
|
|
41
|
+
| Endpoint | Purpose | Required role |
|
|
42
|
+
| :--------------------------------------------------------- | :----------------------------------------------------------- | :------------------------------------------------ |
|
|
43
|
+
| `POST /value/v1/{namespace}/values/{name}` | Write one or more records of a value, with optional metrics. | `value-writer` |
|
|
44
|
+
| `GET /value/v1/{namespace}/values/{name}` | Read records of a value, newest first, with filters. | `value-reader`, or export service `export-job` |
|
|
45
|
+
| `GET /value/v1/{namespace}/values/{name}/count` | Count records of a value. | `value-reader` |
|
|
46
|
+
| `GET /value/v1/{namespace}/values` | Read the latest record of each defined value in a namespace. | `value-reader` |
|
|
47
|
+
| `GET /value/v1/{namespace}/values/{name}/metrics` | Read interval aggregates of a value's metrics. | `value-reader` |
|
|
48
|
+
| `GET /value/v1/{namespace}/values/{name}/metrics/{metric}` | Read interval aggregates of one metric. | `value-reader` |
|
|
49
|
+
| `GET /value/v1/{namespace}/values/{name}/platform-metrics` | Read a value's metrics across all tenants. | `value-platform-metrics-reader` (core users only) |
|
|
50
|
+
| `POST /value/v1/service-metric-rollups/run` | Run the service metric rollup for completed days. | `value-writer` |
|
|
51
|
+
| `GET /value/v1/definitions` | List tenant and core value definitions. | `value-reader` or `value-writer` |
|
|
52
|
+
| `POST /value/v1/definitions` | Create a tenant value definition. | `value-writer` |
|
|
53
|
+
| `GET /value/v1/definitions/{namespace}/{name}` | Get a value definition (tenant, otherwise core). | `value-reader` or `value-writer` |
|
|
54
|
+
| `PATCH /value/v1/definitions/{namespace}/{name}` | Update a tenant value definition. | `value-writer` |
|
|
55
|
+
| `DELETE /value/v1/definitions/{namespace}/{name}` | Delete a tenant value definition. | `value-writer` |
|
|
56
|
+
|
|
57
|
+
The event log has no endpoints of its own in value service. Event log consumers should use the [event service](event-service.md) API, which reads and counts the event log value for them.
|
|
58
|
+
|
|
23
59
|
## Concepts
|
|
24
60
|
|
|
61
|
+
### Value
|
|
62
|
+
|
|
63
|
+
A value represents a particular time series stream, identified by a namespace and name (for example `support` and `application-stats`). Each write results in a new record with a timestamp. It differs from a typical transactional record in that the record has no unique identity; instead it represents another entry in the set of entries for the value. Consumers can write scalars or json objects to values.
|
|
64
|
+
|
|
65
|
+
A record has a `timestamp` (the time of the write unless set), an optional `correlationId` that links related records, an optional `context` object used to filter reads, and the `value` itself. Writing does not require a value definition. A write can be a full record, a bare JSON object that is written as the value, or an array of either.
|
|
66
|
+
|
|
25
67
|
### Value definition
|
|
26
68
|
|
|
27
|
-
Value definition is an optional metadata description for a particular _value_ (identified by a specific namespace and name). The definition provides write-time validation via json schema, and can enable a `value-written` event on each write with `sendWriteEvent`.
|
|
69
|
+
Value definition is an optional metadata description for a particular _value_ (identified by a specific namespace and name). The definition provides write-time validation via json schema, and can enable a `value-written` event on each write with `sendWriteEvent`. Records that fail validation are skipped, and the rest of the write goes ahead. Only values with a definition are returned when reading the latest values of a namespace.
|
|
28
70
|
|
|
29
71
|
Value definitions are managed through the value service definitions API (`/value/v1/definitions`). The value service checks the user's roles and then stores the definitions in the [configuration service](configuration-service.md) under the `platform:value-service` namespace and name, using its own service account. Clients do not need configuration service roles to manage value definitions.
|
|
30
72
|
|
|
@@ -34,23 +76,23 @@ Value definitions are managed through the value service definitions API (`/value
|
|
|
34
76
|
- Creating a definition adds its namespace if it does not exist, and fails with a 409 if a tenant or core definition with the same namespace and name already exists.
|
|
35
77
|
- Deleting the last definition in a namespace removes the namespace.
|
|
36
78
|
|
|
79
|
+
### Event log
|
|
80
|
+
|
|
81
|
+
The event log is a value written by [event service](event-service.md): every logged domain event is written as a record of the `event` value in the `event-service` namespace (`/value/v1/event-service/values/event`), to the tenant of the event. The record's `context` holds the event's context plus its `namespace`, `name` and `trace`, and its `value` is `{ payload }`. Event service also writes metrics with each record: `total:count`, `{namespace}:{name}:count`, and, for event definitions with an interval, a `:duration` metric in seconds since the event that started the interval.
|
|
82
|
+
|
|
37
83
|
> Counting events in the event log is exposed by the [event service](event-service.md#count-events-in-the-event-log).
|
|
38
84
|
> Consumers of the event log count should use that API rather than calling value service directly.
|
|
39
85
|
|
|
40
|
-
|
|
86
|
+
Reads of the event log support exact payload searching with either `payloadPath` and `payloadValue`, or a JSON object in
|
|
41
87
|
`payload`. Both `timestampMin` and `timestampMax` are required for payload searches, and the two search forms are
|
|
42
88
|
mutually exclusive. Every property in a multi-condition `payload` object must match (`AND`). See
|
|
43
89
|
[Search the event log](event-service.md#search-the-event-log) for examples and scalar type handling.
|
|
44
90
|
|
|
45
|
-
### Value
|
|
46
|
-
|
|
47
|
-
A value represents a particular time series stream. Each write results in a new record with a timestamp. It differs from a typical transactional record in that the record has no unique identity; instead it represents another entry in the set of entries for the value. Consumers can write scalars or json objects to values.
|
|
48
|
-
|
|
49
91
|
### Metrics
|
|
50
92
|
|
|
51
|
-
Metrics are numeric values that can be included in value writes as a `metrics` object of metric name to number.
|
|
93
|
+
Metrics are numeric values that can be included in value writes as a `metrics` object of metric name to number; non-numeric entries are ignored, and metrics are not returned with the record. For a value with a definition, a `metrics` property inside the written `value` object is also moved into the record's metrics. Metrics are aggregated into time intervals (`one_minute`, `five_minutes`, `hourly`, `daily`, `weekly` and `monthly`) with `sum`, `avg`, `min`, `max` and `count` for each interval, and can be used for basic KPIs.
|
|
52
94
|
|
|
53
|
-
Read a value's metrics from `/value/v1/{namespace}/values/{name}/metrics`, or a single metric from `/value/v1/{namespace}/values/{name}/metrics/{metric}`. The `interval` defaults to `daily
|
|
95
|
+
Read a value's metrics from `/value/v1/{namespace}/values/{name}/metrics`, or a single metric from `/value/v1/{namespace}/values/{name}/metrics/{metric}`. The `interval` defaults to `daily`; any value other than the six intervals responds 400. The `criteria` query parameter is a JSON object that accepts `intervalMin`, `intervalMax` and (for all metrics) `metricLike`, and must be valid JSON. Without a range, the last month is read. Results are newest first and paged `top` interval rows at a time (default 100, maximum 5000); pass `page.next` back as `after` for the next page.
|
|
54
96
|
|
|
55
97
|
Core users with the `value-platform-metrics-reader` role can read a value's metrics across all tenants, labelled by tenant, from `/value/v1/{namespace}/values/{name}/platform-metrics`. This only reads the materialised rollups described below and is not paginated.
|
|
56
98
|
|
|
@@ -92,6 +134,16 @@ The job is off by default. Set `SERVICE_METRIC_ROLLUP_JOB_ENABLED=true` to run i
|
|
|
92
134
|
|
|
93
135
|
A rollup can also be run on demand with `POST /value/v1/service-metric-rollups/run` and the `value-writer` role. The body can set `start` and `end` dates, which default to the trailing days. Core users can set `tenantId` or leave it out to roll up all tenants; tenant users always roll up their own tenant. The current partial day and future days are rejected.
|
|
94
136
|
|
|
137
|
+
## Events
|
|
138
|
+
|
|
139
|
+
Value service sends one domain event:
|
|
140
|
+
|
|
141
|
+
| Event | Sent when |
|
|
142
|
+
| :-------------- | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
143
|
+
| `value-written` | A record is written to a value whose definition has `sendWriteEvent` set. The payload has `timestamp`, `value` and `writtenBy`, and the context has the record's context plus `namespace` and `name`. |
|
|
144
|
+
|
|
145
|
+
`value-written` events are not written to the event log. Value service doesn't consume domain events; event service writes the event log by calling the value service API, not through an event subscription.
|
|
146
|
+
|
|
95
147
|
## Audit
|
|
96
148
|
|
|
97
149
|
Value service records audit events for administrative changes through the [audit service](audit-service.md), under the `value-service` namespace. Each record includes the actor and the affected resource. Actions do not set a retention class; the audit service derives it from the category (`compliance` for administrative and data-access actions, `standard` for runtime actions), as shown in the table.
|
|
@@ -153,6 +205,39 @@ const { page, ...result } = await response.json();
|
|
|
153
205
|
const records = result[namespace][name];
|
|
154
206
|
```
|
|
155
207
|
|
|
208
|
+
### Read the latest values of a namespace
|
|
209
|
+
|
|
210
|
+
```typescript
|
|
211
|
+
const namespace = 'support';
|
|
212
|
+
const response = await fetch(
|
|
213
|
+
`https://value-service.adsp.alberta.ca/value/v1/${namespace}/values?names=application-stats`,
|
|
214
|
+
{
|
|
215
|
+
method: 'GET',
|
|
216
|
+
headers: { Authorization: `Bearer ${accessToken}` },
|
|
217
|
+
},
|
|
218
|
+
);
|
|
219
|
+
|
|
220
|
+
// Keyed by namespace, then name; each is the latest record.
|
|
221
|
+
const { [namespace]: latest } = await response.json();
|
|
222
|
+
const { timestamp, value } = latest['application-stats'];
|
|
223
|
+
```
|
|
224
|
+
|
|
225
|
+
### Count records
|
|
226
|
+
|
|
227
|
+
```typescript
|
|
228
|
+
const namespace = 'support';
|
|
229
|
+
const name = 'application-stats';
|
|
230
|
+
const response = await fetch(
|
|
231
|
+
`https://value-service.adsp.alberta.ca/value/v1/${namespace}/values/${name}/count?timestampMin=2026-09-01T00:00:00Z`,
|
|
232
|
+
{
|
|
233
|
+
method: 'GET',
|
|
234
|
+
headers: { Authorization: `Bearer ${accessToken}` },
|
|
235
|
+
},
|
|
236
|
+
);
|
|
237
|
+
|
|
238
|
+
const { count } = await response.json();
|
|
239
|
+
```
|
|
240
|
+
|
|
156
241
|
### Read metrics
|
|
157
242
|
|
|
158
243
|
```typescript
|
|
@@ -168,6 +253,7 @@ const response = await fetch(
|
|
|
168
253
|
);
|
|
169
254
|
|
|
170
255
|
// Keyed by metric name; each has values of { interval, sum, avg, min, max, count }, newest first.
|
|
256
|
+
// page.intervalMax is the end of the window actually read.
|
|
171
257
|
const { page, ...metrics } = await response.json();
|
|
172
258
|
```
|
|
173
259
|
|
|
@@ -262,7 +262,7 @@ For additional examples and option reference material, see the [cheat sheet](/ad
|
|
|
262
262
|
ADSP has added several enhancements to the form builder in order to help designers and developers create professional looking forms. These include:
|
|
263
263
|
|
|
264
264
|
- Adding [text, images, and links](/adsp-monorepo/tutorials/form-service/instructions.html) to forms in order to help clarify the information that is needed from end-users when filling them out.
|
|
265
|
-
- A [file upload widget](/adsp-monorepo/tutorials/form-service/file-uploader.
|
|
265
|
+
- A [file upload widget](/adsp-monorepo/tutorials/form-service/file-uploader.html)
|
|
266
266
|
- Data registries
|
|
267
267
|
|
|
268
268
|
## Learn More
|
|
@@ -1264,7 +1264,7 @@ As of **Jan. 2025** you can use markdown for help content, significantly simplif
|
|
|
1264
1264
|
|
|
1265
1265
|
### File Uploads {#target-uploads}
|
|
1266
1266
|
|
|
1267
|
-
For when the user needs to upload supporting documentation. For a more complete description of file uploads, see [the documentation](/adsp-monorepo/tutorials/form-service/file-uploader.
|
|
1267
|
+
For when the user needs to upload supporting documentation. For a more complete description of file uploads, see [the documentation](/adsp-monorepo/tutorials/form-service/file-uploader.html).
|
|
1268
1268
|
|
|
1269
1269
|
<table>
|
|
1270
1270
|
<tr>
|
|
@@ -26,7 +26,7 @@ However, you can also configure a form to allow anonymous access. Anyone will be
|
|
|
26
26
|
|
|
27
27
|
### Security
|
|
28
28
|
|
|
29
|
-
Developers can define the roles that are required to create, review and disposition their forms, as described in the [security section](/adsp-monorepo/tutorials/
|
|
29
|
+
Developers can define the roles that are required to create, review and disposition their forms, as described in the [security section](/adsp-monorepo/tutorials/form-service/security.html) of the tutorial. In addition, they will need the ADSP-specific roles for accessing a form. The former should be specific to your _Tenant_ and _Form Definition_, as they will lock down access so that only your users can log-in and fill in the information. For the _Form App_, a user will need to be an _applicant_. _Clerks_ and _assessors_ will be able to review and disposition this forms through the [Task App](/adsp-monorepo/tutorials/task-service/task-app.html).
|
|
30
30
|
|
|
31
31
|
#### Client Security
|
|
32
32
|
|
|
@@ -34,7 +34,7 @@ _Submission records_ can be used to help manage _Form Disposition_; that is, the
|
|
|
34
34
|
|
|
35
35
|
### Submission Queues
|
|
36
36
|
|
|
37
|
-
In addition, developers can also opt-in to have the submission record placed in a [Task Queue](/adsp-monorepo/tutorials/task-service.html) for further processing:
|
|
37
|
+
In addition, developers can also opt-in to have the submission record placed in a [Task Queue](/adsp-monorepo/tutorials/task-service/task-queues.html) for further processing:
|
|
38
38
|
|
|
39
39
|
{: width="400" }
|
|
40
40
|
|
|
@@ -18,7 +18,7 @@ Jsonforms provides a declarative means for creating new form definitions. Develo
|
|
|
18
18
|
|
|
19
19
|
### Rendering
|
|
20
20
|
|
|
21
|
-
Currently the Form Service only supports rendering forms in React applications through a Jsonforms React component. [Adding it to your application](/adsp-monorepo/tutorials/form-service/
|
|
21
|
+
Currently the Form Service only supports rendering forms in React applications through a Jsonforms React component. [Adding it to your application](/adsp-monorepo/tutorials/form-service/Integration.html) enables it to:
|
|
22
22
|
|
|
23
23
|
- render the form,
|
|
24
24
|
- secure access to it,
|
|
@@ -28,7 +28,7 @@ There are several roles that may be required for users to access the form servic
|
|
|
28
28
|
|
|
29
29
|
{: width="600" }
|
|
30
30
|
|
|
31
|
-
Applicants
|
|
31
|
+
Applicants create and fill out forms with the applicant roles of the _Form Definition_, and need the _form-applicant_ role to receive updates in the form app. The _form-admin_ role is for form administrators, and the _intake-application_ role is for service accounts that create and submit forms on behalf of anonymous applicants. If the form requires files to be uploaded applicants will also need:
|
|
32
32
|
|
|
33
33
|
- _form-file-reader_
|
|
34
34
|
- _form-file-uploader_
|
|
@@ -40,7 +40,7 @@ Click _start health check_ to begin the pinging. The status bar will update ever
|
|
|
40
40
|
|
|
41
41
|
### APIs
|
|
42
42
|
|
|
43
|
-
You can also monitor and control the pings via the [Status Service APIs](https://api.adsp
|
|
43
|
+
You can also monitor and control the pings via the [Status Service APIs](https://api.adsp.alberta.ca), from another application. This would only be necessary if you wished to automate control, provide your own interface to keep user's notified, or perhaps to perform automated diagnostic on the application in question. The [Tenant Management Webapp](https://adsp.alberta.ca) provides basic capabilities for doing these things manually.
|
|
44
44
|
|
|
45
45
|
## Learn More
|
|
46
46
|
|
|
@@ -8,7 +8,7 @@ grand_parent: Tutorials
|
|
|
8
8
|
|
|
9
9
|
## Application Status
|
|
10
10
|
|
|
11
|
-
Application status is the _operational status_ of your application that can be set manually through the Status Service page on the [Tenant Admin Webapp](https://adsp.alberta.ca) or automatically, by integrating the [status service APIs](https://api.adsp
|
|
11
|
+
Application status is the _operational status_ of your application that can be set manually through the Status Service page on the [Tenant Admin Webapp](https://adsp.alberta.ca) or automatically, by integrating the [status service APIs](https://api.adsp.alberta.ca) with your application. Operational status can take on one of four values:
|
|
12
12
|
|
|
13
13
|
- Operational: The application is up and running,
|
|
14
14
|
- Maintenance: The application is undergoing routine maintenance,
|
|
@@ -26,7 +26,7 @@ Changing an application's status can affect users in a couple of ways. It will
|
|
|
26
26
|
- update the status on the public static webpage provided for your tenant, and
|
|
27
27
|
- notify anyone who has subscribed for notification of change. This includes end users.
|
|
28
28
|
|
|
29
|
-
The public status page for your tenant can be found at at https://status.adsp.alberta.ca/{tenant-name}. Linking to this will give your users information about your tenant applications, including any [notices](/adsp-monorepo/tutorials/status-service/
|
|
29
|
+
The public status page for your tenant can be found at at https://status.adsp.alberta.ca/{tenant-name}. Linking to this will give your users information about your tenant applications, including any [notices](/adsp-monorepo/tutorials/status-service/notices.html) you may have posted. The latter gives you the ability to post information about a status change, including expected times. This is useful, for example, to inform users of upcoming maintenance windows or current outages.
|
|
30
30
|
|
|
31
31
|
## Learn More
|
|
32
32
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@abgov/adsp-sdk-mcp-server",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.24.1",
|
|
4
4
|
"license": "Apache-2.0",
|
|
5
5
|
"description": "Government of Alberta - MCP server for ADSP documentation and Node SDK reference lookup.",
|
|
6
6
|
"repository": "https://github.com/GovAlta/adsp-monorepo",
|
|
@@ -15,6 +15,7 @@
|
|
|
15
15
|
"@opentelemetry/resources": "2.10.0",
|
|
16
16
|
"@opentelemetry/sdk-metrics": "2.10.0",
|
|
17
17
|
"express": "^4.21.0",
|
|
18
|
+
"express-rate-limit": "^7.1.4",
|
|
18
19
|
"tslib": "^2.3.0",
|
|
19
20
|
"zod": "^4.6.7"
|
|
20
21
|
},
|
package/src/config.d.ts
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
export interface McpServerConfig {
|
|
2
|
+
maxInFlight: number;
|
|
3
|
+
inFlightWaitMs: number;
|
|
4
|
+
/** 0 disables the rate limit. */
|
|
5
|
+
rateLimitPerMinute: number;
|
|
6
|
+
liveToolMaxConcurrent: number;
|
|
7
|
+
/** Passed to Express `trust proxy`. */
|
|
8
|
+
trustedProxy: boolean | number | string;
|
|
9
|
+
corsOrigins: '*' | string[];
|
|
10
|
+
}
|
|
11
|
+
export declare function readConfig(env?: NodeJS.ProcessEnv): McpServerConfig;
|
package/src/config.js
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.readConfig = readConfig;
|
|
4
|
+
function readInteger(env, name, defaultValue, minimum) {
|
|
5
|
+
const raw = env[name]?.trim();
|
|
6
|
+
if (!raw) {
|
|
7
|
+
return defaultValue;
|
|
8
|
+
}
|
|
9
|
+
if (!/^\d+$/.test(raw) || Number(raw) < minimum) {
|
|
10
|
+
throw new Error(`${name} must be an integer of at least ${minimum}, but is "${raw}".`);
|
|
11
|
+
}
|
|
12
|
+
return Number(raw);
|
|
13
|
+
}
|
|
14
|
+
function readTrustedProxy(env) {
|
|
15
|
+
const raw = env['TRUSTED_PROXY']?.trim();
|
|
16
|
+
if (!raw) {
|
|
17
|
+
return 'uniquelocal';
|
|
18
|
+
}
|
|
19
|
+
if (raw === 'true' || raw === 'false') {
|
|
20
|
+
return raw === 'true';
|
|
21
|
+
}
|
|
22
|
+
return /^\d+$/.test(raw) ? Number(raw) : raw;
|
|
23
|
+
}
|
|
24
|
+
function readCorsOrigins(env) {
|
|
25
|
+
const origins = (env['CORS_ORIGIN'] ?? '')
|
|
26
|
+
.split(',')
|
|
27
|
+
.map((origin) => origin.trim().replace(/\/+$/, ''))
|
|
28
|
+
.filter(Boolean);
|
|
29
|
+
if (!origins.includes('*')) {
|
|
30
|
+
return origins;
|
|
31
|
+
}
|
|
32
|
+
if (origins.length > 1) {
|
|
33
|
+
throw new Error('CORS_ORIGIN must be either * or a list of origins, not both.');
|
|
34
|
+
}
|
|
35
|
+
return '*';
|
|
36
|
+
}
|
|
37
|
+
function readConfig(env = process.env) {
|
|
38
|
+
return {
|
|
39
|
+
maxInFlight: readInteger(env, 'MCP_MAX_IN_FLIGHT', 64, 1),
|
|
40
|
+
inFlightWaitMs: readInteger(env, 'MCP_IN_FLIGHT_WAIT_MS', 1000, 0),
|
|
41
|
+
rateLimitPerMinute: readInteger(env, 'MCP_RATE_LIMIT_PER_MINUTE', 1200, 0),
|
|
42
|
+
liveToolMaxConcurrent: readInteger(env, 'MCP_LIVE_TOOL_MAX_CONCURRENT', 8, 1),
|
|
43
|
+
trustedProxy: readTrustedProxy(env),
|
|
44
|
+
corsOrigins: readCorsOrigins(env),
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
//# sourceMappingURL=config.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"config.js","sourceRoot":"","sources":["../../../../libs/adsp-sdk-mcp-server/src/config.ts"],"names":[],"mappings":";;AA+CA,gCASC;AA7CD,SAAS,WAAW,CAAC,GAAsB,EAAE,IAAY,EAAE,YAAoB,EAAE,OAAe;IAC9F,MAAM,GAAG,GAAG,GAAG,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,CAAC;IAC9B,IAAI,CAAC,GAAG,EAAE,CAAC;QACT,OAAO,YAAY,CAAC;IACtB,CAAC;IACD,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,GAAG,CAAC,IAAI,MAAM,CAAC,GAAG,CAAC,GAAG,OAAO,EAAE,CAAC;QAChD,MAAM,IAAI,KAAK,CAAC,GAAG,IAAI,mCAAm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W,CAAC,GAAG,EAAE,uBAAuB,EAAE,IAAI,EAAE,CAAC,CAAC;QAClE,kBAAkB,EAAE,WAAW,CAAC,GAAG,EAAE,2BAA2B,EAAE,IAAI,EAAE,CAAC,CAAC;QAC1E,qBAAqB,EAAE,WAAW,CAAC,GAAG,EAAE,8BAA8B,EAAE,CAAC,EAAE,CAAC,CAAC;QAC7E,YAAY,EAAE,gBAAgB,CAAC,GAAG,CAAC;QACnC,WAAW,EAAE,eAAe,CAAC,GAAG,CAAC;KAClC,CAAC;AACJ,CAAC"}
|
package/src/guards.d.ts
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import type * as express from 'express';
|
|
2
|
+
import { McpServerConfig } from './config';
|
|
3
|
+
import { Semaphore } from './semaphore';
|
|
4
|
+
export declare function sendJsonRpcError(res: express.Response, status: number, message: string): void;
|
|
5
|
+
/** MCP requires servers to validate Origin (2025-11-25). Requests without one come from non-browser clients and pass. */
|
|
6
|
+
export declare function createCorsAndOriginGuard(corsOrigins: McpServerConfig['corsOrigins']): express.RequestHandler;
|
|
7
|
+
/** Keyed by client IP until authentication lands; then this should return the authenticated client. */
|
|
8
|
+
export declare function rateLimitKey(req: express.Request): string;
|
|
9
|
+
export declare function createRateLimit(limitPerMinute: number): express.RequestHandler;
|
|
10
|
+
/** Holds each admitted request's slot until its response closes; `mcp.requests.in_flight` counts admitted requests. */
|
|
11
|
+
export declare function createInFlightGate(semaphore: Semaphore, waitMs: number): express.RequestHandler;
|
package/src/guards.js
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.sendJsonRpcError = sendJsonRpcError;
|
|
4
|
+
exports.createCorsAndOriginGuard = createCorsAndOriginGuard;
|
|
5
|
+
exports.rateLimitKey = rateLimitKey;
|
|
6
|
+
exports.createRateLimit = createRateLimit;
|
|
7
|
+
exports.createInFlightGate = createInFlightGate;
|
|
8
|
+
const express_rate_limit_1 = require("express-rate-limit");
|
|
9
|
+
const metrics_1 = require("./metrics");
|
|
10
|
+
const RATE_LIMIT_WINDOW_MS = 60_000;
|
|
11
|
+
function sendJsonRpcError(res, status, message) {
|
|
12
|
+
res.status(status).json({ jsonrpc: '2.0', error: { code: -32000, message }, id: null });
|
|
13
|
+
}
|
|
14
|
+
function isAllowedOrigin(origin, corsOrigins) {
|
|
15
|
+
// Sandboxed frames and file: pages send "null", which can't be tied to any one site.
|
|
16
|
+
if (origin === 'null') {
|
|
17
|
+
return false;
|
|
18
|
+
}
|
|
19
|
+
// Exact match: browsers send Origin as scheme://host[:port], and trimming the client's value with a regex is
|
|
20
|
+
// quadratic on a header full of slashes. CORS_ORIGIN entries are normalised once in readConfig instead.
|
|
21
|
+
return corsOrigins === '*' || corsOrigins.includes(origin);
|
|
22
|
+
}
|
|
23
|
+
/** MCP requires servers to validate Origin (2025-11-25). Requests without one come from non-browser clients and pass. */
|
|
24
|
+
function createCorsAndOriginGuard(corsOrigins) {
|
|
25
|
+
return (req, res, next) => {
|
|
26
|
+
res.vary('Origin');
|
|
27
|
+
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, DELETE, OPTIONS');
|
|
28
|
+
res.setHeader('Access-Control-Allow-Headers', 'Content-Type, mcp-session-id, mcp-protocol-version');
|
|
29
|
+
res.setHeader('Access-Control-Expose-Headers', 'mcp-session-id');
|
|
30
|
+
const origin = req.headers.origin;
|
|
31
|
+
if (origin !== undefined) {
|
|
32
|
+
if (!isAllowedOrigin(origin, corsOrigins)) {
|
|
33
|
+
(0, metrics_1.getMetrics)().recordRejection('origin');
|
|
34
|
+
sendJsonRpcError(res, 403, 'Origin not allowed');
|
|
35
|
+
return;
|
|
36
|
+
}
|
|
37
|
+
res.setHeader('Access-Control-Allow-Origin', corsOrigins === '*' ? '*' : origin);
|
|
38
|
+
}
|
|
39
|
+
if (req.method === 'OPTIONS') {
|
|
40
|
+
res.sendStatus(204);
|
|
41
|
+
return;
|
|
42
|
+
}
|
|
43
|
+
next();
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
/** Keyed by client IP until authentication lands; then this should return the authenticated client. */
|
|
47
|
+
function rateLimitKey(req) {
|
|
48
|
+
return req.ip ?? 'unknown';
|
|
49
|
+
}
|
|
50
|
+
function createRateLimit(limitPerMinute) {
|
|
51
|
+
if (limitPerMinute === 0) {
|
|
52
|
+
return (_req, _res, next) => next();
|
|
53
|
+
}
|
|
54
|
+
return (0, express_rate_limit_1.rateLimit)({
|
|
55
|
+
windowMs: RATE_LIMIT_WINDOW_MS,
|
|
56
|
+
limit: limitPerMinute,
|
|
57
|
+
standardHeaders: 'draft-7',
|
|
58
|
+
legacyHeaders: false,
|
|
59
|
+
keyGenerator: rateLimitKey,
|
|
60
|
+
// With standardHeaders on, express-rate-limit sets Retry-After before calling the handler.
|
|
61
|
+
handler: (_req, res) => {
|
|
62
|
+
(0, metrics_1.getMetrics)().recordRejection('rate_limit');
|
|
63
|
+
sendJsonRpcError(res, 429, 'Rate limit exceeded');
|
|
64
|
+
},
|
|
65
|
+
});
|
|
66
|
+
}
|
|
67
|
+
/** Holds each admitted request's slot until its response closes; `mcp.requests.in_flight` counts admitted requests. */
|
|
68
|
+
function createInFlightGate(semaphore, waitMs) {
|
|
69
|
+
return async (_req, res, next) => {
|
|
70
|
+
const closed = new AbortController();
|
|
71
|
+
res.on('close', () => closed.abort());
|
|
72
|
+
const release = await semaphore.acquire(waitMs, closed.signal);
|
|
73
|
+
if (!release) {
|
|
74
|
+
if (!closed.signal.aborted) {
|
|
75
|
+
(0, metrics_1.getMetrics)().recordRejection('in_flight_cap');
|
|
76
|
+
res.setHeader('Retry-After', '1');
|
|
77
|
+
sendJsonRpcError(res, 503, 'Server busy');
|
|
78
|
+
}
|
|
79
|
+
return;
|
|
80
|
+
}
|
|
81
|
+
if (closed.signal.aborted) {
|
|
82
|
+
release();
|
|
83
|
+
return;
|
|
84
|
+
}
|
|
85
|
+
const metrics = (0, metrics_1.getMetrics)();
|
|
86
|
+
metrics.addInFlight(1);
|
|
87
|
+
res.on('close', () => {
|
|
88
|
+
release();
|
|
89
|
+
metrics.addInFlight(-1);
|
|
90
|
+
});
|
|
91
|
+
next();
|
|
92
|
+
};
|
|
93
|
+
}
|
|
94
|
+
//# sourceMappingURL=guards.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"guards.js","sourceRoot":"","sources":["../../../../libs/adsp-sdk-mcp-server/src/guards.ts"],"names":[],"mappings":";;AAQA,4CAEC;AAaD,4DAuBC;AAGD,oCAEC;AAED,0CAgBC;AAGD,gDA2BC;AAlGD,2DAA+C;AAE/C,uCAAuC;AAGvC,MAAM,oBAAoB,GAAG,MAAM,CAAC;AAEpC,SAAgB,gBAAgB,CAAC,GAAqB,EAAE,MAAc,EAAE,OAAe;IACrF,GAAG,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,IAAI,CAAC,EAAE,OAAO,EAAE,KAAK,EAAE,KAAK,EAAE,EAAE,IAAI,EAAE,CAAC,KAAK,EAAE,OAAO,EAAE,EAAE,EAAE,EAAE,IAAI,EAAE,CAAC,CAAC;AAC1F,CAAC;AAED,SAAS,eAAe,CAAC,MAAc,EAAE,WAA2C;IAClF,qFAAqF;IACrF,IAAI,MAAM,KAAK,MAAM,EAAE,CAAC;QACtB,OAAO,KAAK,CAAC;IACf,CAAC;IACD,6GAA6G;IAC7G,wGAAwG;IACxG,OAAO,WAAW,KAAK,GAAG,IAAI,WAAW,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC;AAC7D,CAAC;AAED,yHAAyH;AACzH,SAAgB,wBAAwB,CAAC,WAA2C;IAClF,OAAO,CAAC,GAAG,EAAE,GAAG,EAAE,IAAI,EAAE,EAAE;QACxB,GAAG,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;QACnB,GAAG,CAAC,SAAS,CAAC,8BAA8B,EAAE,4BAA4B,CAAC,CAAC;QAC5E,GAAG,CAAC,SAAS,CAAC,8B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,CAAC;IACT,CAAC,CAAC;AACJ,CAAC"}
|
package/src/http.d.ts
CHANGED
|
@@ -1,3 +1,19 @@
|
|
|
1
1
|
import * as express from 'express';
|
|
2
|
+
import { Server as HttpServer } from 'http';
|
|
3
|
+
import { McpServerConfig } from './config';
|
|
2
4
|
import { CreateAdspMcpServerOptions } from './server';
|
|
3
|
-
export
|
|
5
|
+
export interface McpHttpAppOptions extends CreateAdspMcpServerOptions {
|
|
6
|
+
/** Defaults to `readConfig()` over `process.env`. */
|
|
7
|
+
config?: McpServerConfig;
|
|
8
|
+
}
|
|
9
|
+
export declare function createMcpHttpApp({ config, ...serverOptions }?: McpHttpAppOptions): express.Express;
|
|
10
|
+
export interface McpHttpServerOptions {
|
|
11
|
+
requestTimeoutMs?: number;
|
|
12
|
+
headersTimeoutMs?: number;
|
|
13
|
+
connectionsCheckingIntervalMs?: number;
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* The in-flight gate admits a request before its body arrives, so a client that never finishes sending one would hold
|
|
17
|
+
* a slot until Node's 300 s default. These limits only cover receiving the request, not how long a tool call takes.
|
|
18
|
+
*/
|
|
19
|
+
export declare function createMcpHttpServer(app: express.Express, options?: McpHttpServerOptions): HttpServer;
|
package/src/http.js
CHANGED
|
@@ -1,30 +1,24 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.createMcpHttpApp = createMcpHttpApp;
|
|
4
|
+
exports.createMcpHttpServer = createMcpHttpServer;
|
|
4
5
|
const streamableHttp_js_1 = require("@modelcontextprotocol/sdk/server/streamableHttp.js");
|
|
5
6
|
const express = require("express");
|
|
7
|
+
const http_1 = require("http");
|
|
6
8
|
const perf_hooks_1 = require("perf_hooks");
|
|
9
|
+
const config_1 = require("./config");
|
|
10
|
+
const guards_1 = require("./guards");
|
|
7
11
|
const metrics_1 = require("./metrics");
|
|
12
|
+
const semaphore_1 = require("./semaphore");
|
|
8
13
|
const server_1 = require("./server");
|
|
14
|
+
const liveToolLimit_1 = require("./tools/liveToolLimit");
|
|
9
15
|
const MAX_REQUEST_BODY_BYTES = 1024 * 1024;
|
|
10
|
-
function applyCorsHeaders(req, res, next) {
|
|
11
|
-
res.setHeader('Access-Control-Allow-Origin', process.env['CORS_ORIGIN'] ?? '*');
|
|
12
|
-
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, DELETE, OPTIONS');
|
|
13
|
-
res.setHeader('Access-Control-Allow-Headers', 'Content-Type, mcp-session-id, mcp-protocol-version');
|
|
14
|
-
res.setHeader('Access-Control-Expose-Headers', 'mcp-session-id');
|
|
15
|
-
if (req.method === 'OPTIONS') {
|
|
16
|
-
res.sendStatus(204);
|
|
17
|
-
return;
|
|
18
|
-
}
|
|
19
|
-
next();
|
|
20
|
-
}
|
|
21
16
|
function createStatelessPostHandler(options) {
|
|
22
17
|
return async (req, res) => {
|
|
23
18
|
const started = perf_hooks_1.performance.now();
|
|
24
19
|
const metrics = (0, metrics_1.getMetrics)();
|
|
25
20
|
let method = 'unparsed';
|
|
26
21
|
let messagesSeen = 0;
|
|
27
|
-
metrics.addInFlight(1);
|
|
28
22
|
const server = (0, server_1.createAdspMcpServer)(options);
|
|
29
23
|
const transport = new streamableHttp_js_1.StreamableHTTPServerTransport({
|
|
30
24
|
sessionIdGenerator: undefined,
|
|
@@ -35,7 +29,6 @@ function createStatelessPostHandler(options) {
|
|
|
35
29
|
res.on('close', () => {
|
|
36
30
|
transport.close();
|
|
37
31
|
server.close();
|
|
38
|
-
metrics.addInFlight(-1);
|
|
39
32
|
// Node leaves statusCode at 200 when the client goes away before a response is written.
|
|
40
33
|
const outcome = res.writableFinished ? res.statusCode : 'aborted';
|
|
41
34
|
metrics.recordRequest(method, outcome, (perf_hooks_1.performance.now() - started) / 1000);
|
|
@@ -70,17 +63,30 @@ function methodNotAllowed(_req, res) {
|
|
|
70
63
|
.set('Allow', 'POST')
|
|
71
64
|
.json({ jsonrpc: '2.0', error: { code: -32000, message: 'Method not allowed.' }, id: null });
|
|
72
65
|
}
|
|
73
|
-
function createMcpHttpApp(
|
|
74
|
-
(0, server_1.loadAdspMcpTools)(
|
|
66
|
+
function createMcpHttpApp({ config = (0, config_1.readConfig)(), ...serverOptions } = {}) {
|
|
67
|
+
(0, server_1.loadAdspMcpTools)(serverOptions);
|
|
68
|
+
(0, liveToolLimit_1.configureLiveToolLimit)({ maxConcurrent: config.liveToolMaxConcurrent, waitMs: config.inFlightWaitMs });
|
|
75
69
|
// No express.json(): the transport reads the body so parse and size errors come back as JSON-RPC.
|
|
76
70
|
const app = express();
|
|
77
|
-
app.
|
|
71
|
+
app.set('trust proxy', config.trustedProxy);
|
|
78
72
|
app.get('/health', (_req, res) => {
|
|
79
73
|
res.json({ status: 'ok' });
|
|
80
74
|
});
|
|
81
|
-
app.
|
|
75
|
+
app.use('/mcp', (0, guards_1.createCorsAndOriginGuard)(config.corsOrigins));
|
|
76
|
+
app.post('/mcp', (0, guards_1.createRateLimit)(config.rateLimitPerMinute), (0, guards_1.createInFlightGate)(new semaphore_1.Semaphore(config.maxInFlight, { maxWaiters: config.maxInFlight }), config.inFlightWaitMs), createStatelessPostHandler(serverOptions));
|
|
82
77
|
app.get('/mcp', methodNotAllowed);
|
|
83
78
|
app.delete('/mcp', methodNotAllowed);
|
|
84
79
|
return app;
|
|
85
80
|
}
|
|
81
|
+
/**
|
|
82
|
+
* The in-flight gate admits a request before its body arrives, so a client that never finishes sending one would hold
|
|
83
|
+
* a slot until Node's 300 s default. These limits only cover receiving the request, not how long a tool call takes.
|
|
84
|
+
*/
|
|
85
|
+
function createMcpHttpServer(app, options = {}) {
|
|
86
|
+
return (0, http_1.createServer)({
|
|
87
|
+
requestTimeout: options.requestTimeoutMs ?? 30_000,
|
|
88
|
+
headersTimeout: options.headersTimeoutMs ?? 20_000,
|
|
89
|
+
connectionsCheckingInterval: options.connectionsCheckingIntervalMs ?? 5_000,
|
|
90
|
+
}, app);
|
|
91
|
+
}
|
|
86
92
|
//# sourceMappingURL=http.js.map
|
package/src/http.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"http.js","sourceRoot":"","sources":["../../../../libs/adsp-sdk-mcp-server/src/http.ts"],"names":[],"mappings":";;
|
|
1
|
+
{"version":3,"file":"http.js","sourceRoot":"","sources":["../../../../libs/adsp-sdk-mcp-server/src/http.ts"],"names":[],"mappings":";;AAwEA,4CAuBC;AAYD,kDASC;AApHD,0FAAmG;AACnG,mCAAmC;AACnC,+BAA0D;AAC1D,2CAAyC;AACzC,qCAAuD;AACvD,qCAAyF;AACzF,uCAAwD;AACxD,2CAAwC;AACxC,qCAA6F;AAC7F,yDAA+D;AAE/D,MAAM,sBAAsB,GAAG,IAAI,GAAG,IAAI,CAAC;AAO3C,SAAS,0BAA0B,CAAC,OAAmC;IACrE,OAAO,KAAK,EAAE,GAAG,EAAE,GAAG,EAAE,EAAE;QACxB,MAAM,OAAO,GAAG,wBAAW,CAAC,GAAG,EAAE,CAAC;QAClC,MAAM,OAAO,GAAG,IAAA,oBAAU,GAAE,CAAC;QAC7B,IAAI,MAAM,GAAG,UAAU,CAAC;QACxB,IAAI,YAAY,GAAG,CAAC,CAAC;QAErB,MAAM,MAAM,GAAG,IAAA,4BAAmB,EAAC,OAAO,CAAC,CAAC;QAC5C,MAAM,SAAS,GAAG,IAAI,iDAA6B,CAAC;YAClD,kBAAkB,EAAE,SAAS;YAC7B,kBAAkB,EAAE,IAAI;YACxB,kBAAkB,EAAE,sBAAsB;SAC3C,CAAC,CAAC;QACH,kGAAkG;QAClG,GAAG,CAAC,EAAE,CAAC,OAAO,EAAE,GAAG,EAAE;YACnB,SAAS,CAAC,KAAK,EAAE,CAAC;YAClB,MAAM,CAAC,KAAK,EAAE,CAAC;YACf,wFAAwF;YACxF,MAAM,OAAO,GAAG,GAAG,CAAC,gBAAgB,CAAC,CAAC,CAAC,GAAG,CAAC,UAAU,CAAC,CAAC,CAAC,SAAS,CAAC;YAClE,OAAO,C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,CAAC,CAAC;IAClC,GAAG,CAAC,MAAM,CAAC,MAAM,EAAE,gBAAgB,CAAC,CAAC;IAErC,OAAO,GAAG,CAAC;AACb,CAAC;AAQD;;;GAGG;AACH,SAAgB,mBAAmB,CAAC,GAAoB,EAAE,UAAgC,EAAE;IAC1F,OAAO,IAAA,mBAAY,EACjB;QACE,cAAc,EAAE,OAAO,CAAC,gBAAgB,IAAI,MAAM;QAClD,cAAc,EAAE,OAAO,CAAC,gBAAgB,IAAI,MAAM;QAClD,2BAA2B,EAAE,OAAO,CAAC,6BAA6B,IAAI,KAAK;KAC5E,EACD,GAAG,CACJ,CAAC;AACJ,CAAC"}
|
package/src/main.js
CHANGED
|
@@ -2,9 +2,11 @@
|
|
|
2
2
|
"use strict";
|
|
3
3
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
4
4
|
const stdio_js_1 = require("@modelcontextprotocol/sdk/server/stdio.js");
|
|
5
|
+
const config_1 = require("./config");
|
|
5
6
|
const http_1 = require("./http");
|
|
6
7
|
const metrics_1 = require("./metrics");
|
|
7
8
|
const server_1 = require("./server");
|
|
9
|
+
const liveToolLimit_1 = require("./tools/liveToolLimit");
|
|
8
10
|
function resolveTransport() {
|
|
9
11
|
const raw = process.env['MCP_TRANSPORT'] ?? 'stdio';
|
|
10
12
|
if (raw === 'stdio' || raw === 'http')
|
|
@@ -14,22 +16,24 @@ function resolveTransport() {
|
|
|
14
16
|
}
|
|
15
17
|
async function main() {
|
|
16
18
|
const transport = resolveTransport();
|
|
19
|
+
const config = (0, config_1.readConfig)();
|
|
17
20
|
console.error(`[adsp-sdk-mcp-server] transport=${transport}`);
|
|
18
21
|
if (transport === 'http') {
|
|
19
|
-
await startHttp();
|
|
22
|
+
await startHttp(config);
|
|
20
23
|
}
|
|
21
24
|
else {
|
|
25
|
+
(0, liveToolLimit_1.configureLiveToolLimit)({ maxConcurrent: config.liveToolMaxConcurrent, waitMs: config.inFlightWaitMs });
|
|
22
26
|
const server = (0, server_1.createAdspMcpServer)();
|
|
23
27
|
await server.connect(new stdio_js_1.StdioServerTransport());
|
|
24
28
|
}
|
|
25
29
|
}
|
|
26
|
-
async function startHttp() {
|
|
30
|
+
async function startHttp(config) {
|
|
27
31
|
const port = parseInt(process.env['PORT'] ?? '3000', 10);
|
|
28
32
|
// Started before the app so the docs index build, which the app triggers, is recorded.
|
|
29
33
|
const metrics = await (0, metrics_1.startMetricsFromEnv)();
|
|
30
|
-
const app = (0, http_1.createMcpHttpApp)();
|
|
34
|
+
const app = (0, http_1.createMcpHttpApp)({ config });
|
|
31
35
|
return new Promise((resolve) => {
|
|
32
|
-
const httpServer = app.listen(port, () => {
|
|
36
|
+
const httpServer = (0, http_1.createMcpHttpServer)(app).listen(port, () => {
|
|
33
37
|
console.error(`[adsp-sdk-mcp-server] HTTP server listening on :${port}`);
|
|
34
38
|
resolve();
|
|
35
39
|
});
|