@corsenai/corsen-context-astro 1.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +35 -0
- package/dist/index.d.mts +45 -0
- package/dist/index.d.ts +45 -0
- package/dist/index.js +201 -0
- package/dist/index.mjs +176 -0
- package/package.json +60 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Corsen AI
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
# @corsenai/corsen-context-astro
|
|
2
|
+
|
|
3
|
+
Astro adapter for **[Corsen Context](https://github.com/CorsenAI/corsen-context)** — drop-in API route handlers for the MCP endpoint and `llms.txt`, with built-in auth, rate limiting, CORS, and security headers. Uses Astro's `clientAddress` for accurate rate limiting.
|
|
4
|
+
|
|
5
|
+
> Requires Astro SSR (`output: 'server'` or `'hybrid'`).
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
npm install @corsenai/corsen-context @corsenai/corsen-context-astro
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
**MCP endpoint** — `src/pages/v1/mcp.ts`:
|
|
12
|
+
|
|
13
|
+
```typescript
|
|
14
|
+
import { createMCPHandler } from '@corsenai/corsen-context-astro';
|
|
15
|
+
import { siteProvider } from '../../lib/corsen-provider';
|
|
16
|
+
|
|
17
|
+
export const { POST, OPTIONS } = createMCPHandler(
|
|
18
|
+
{ siteUrl: import.meta.env.SITE ?? 'https://example.com' },
|
|
19
|
+
siteProvider,
|
|
20
|
+
);
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
**llms.txt** — `src/pages/llms.txt.ts`:
|
|
24
|
+
|
|
25
|
+
```typescript
|
|
26
|
+
import { createLlmsTxtHandler } from '@corsenai/corsen-context-astro';
|
|
27
|
+
import { siteProvider } from '../lib/corsen-provider';
|
|
28
|
+
|
|
29
|
+
export const GET = createLlmsTxtHandler({ siteUrl: import.meta.env.SITE }, siteProvider);
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
For production (multi-instance), pass a Redis cache and rate-limit store via the third `options` argument (`{ cache, rateLimitStore, logger }`).
|
|
33
|
+
|
|
34
|
+
- **Full docs:** https://github.com/CorsenAI/corsen-context#readme
|
|
35
|
+
- **License:** MIT
|
package/dist/index.d.mts
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import { CacheDriver, RateLimitStore, Logger, CorsenContextConfig, ContentProvider } from '@corsenai/corsen-context';
|
|
2
|
+
export { CacheDriver, ContentProvider, CorsenContextConfig, Logger, RateLimitStore } from '@corsenai/corsen-context';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Optional production wiring for the Astro handlers — inject the same
|
|
6
|
+
* distributed cache, rate-limit store, and logger the core supports.
|
|
7
|
+
*/
|
|
8
|
+
interface HandlerOptions {
|
|
9
|
+
cache?: CacheDriver;
|
|
10
|
+
rateLimitStore?: RateLimitStore;
|
|
11
|
+
logger?: Logger;
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* The subset of Astro's APIContext the handlers use. `clientAddress` is the real
|
|
15
|
+
* socket peer address the Astro server adapter resolves — better than a header
|
|
16
|
+
* guess for rate limiting.
|
|
17
|
+
*/
|
|
18
|
+
interface AstroContext {
|
|
19
|
+
request: Request;
|
|
20
|
+
clientAddress?: string;
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* Creates an Astro API route handler for the MCP endpoint (POST /v1/mcp).
|
|
24
|
+
*
|
|
25
|
+
* Usage (src/pages/v1/mcp.ts):
|
|
26
|
+
* ```ts
|
|
27
|
+
* import { createMCPHandler } from '@corsenai/corsen-context-astro';
|
|
28
|
+
* import { siteProvider } from '../../lib/corsen-provider';
|
|
29
|
+
*
|
|
30
|
+
* export const { POST, OPTIONS } = createMCPHandler(
|
|
31
|
+
* { siteUrl: import.meta.env.SITE ?? 'https://example.com' },
|
|
32
|
+
* siteProvider,
|
|
33
|
+
* );
|
|
34
|
+
* ```
|
|
35
|
+
*/
|
|
36
|
+
declare function createMCPHandler(config: CorsenContextConfig, provider: ContentProvider, options?: HandlerOptions): {
|
|
37
|
+
POST: (context: AstroContext) => Promise<Response>;
|
|
38
|
+
OPTIONS: (context: AstroContext) => Promise<Response>;
|
|
39
|
+
};
|
|
40
|
+
/** Creates an Astro GET handler that serves /llms.txt. */
|
|
41
|
+
declare function createLlmsTxtHandler(config: CorsenContextConfig, provider: ContentProvider, options?: HandlerOptions): () => Promise<Response>;
|
|
42
|
+
/** Creates an Astro GET handler that serves /llms-full.txt. */
|
|
43
|
+
declare function createLlmsFullTxtHandler(config: CorsenContextConfig, provider: ContentProvider, options?: HandlerOptions): () => Promise<Response>;
|
|
44
|
+
|
|
45
|
+
export { type AstroContext, type HandlerOptions, createLlmsFullTxtHandler, createLlmsTxtHandler, createMCPHandler };
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import { CacheDriver, RateLimitStore, Logger, CorsenContextConfig, ContentProvider } from '@corsenai/corsen-context';
|
|
2
|
+
export { CacheDriver, ContentProvider, CorsenContextConfig, Logger, RateLimitStore } from '@corsenai/corsen-context';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Optional production wiring for the Astro handlers — inject the same
|
|
6
|
+
* distributed cache, rate-limit store, and logger the core supports.
|
|
7
|
+
*/
|
|
8
|
+
interface HandlerOptions {
|
|
9
|
+
cache?: CacheDriver;
|
|
10
|
+
rateLimitStore?: RateLimitStore;
|
|
11
|
+
logger?: Logger;
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* The subset of Astro's APIContext the handlers use. `clientAddress` is the real
|
|
15
|
+
* socket peer address the Astro server adapter resolves — better than a header
|
|
16
|
+
* guess for rate limiting.
|
|
17
|
+
*/
|
|
18
|
+
interface AstroContext {
|
|
19
|
+
request: Request;
|
|
20
|
+
clientAddress?: string;
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* Creates an Astro API route handler for the MCP endpoint (POST /v1/mcp).
|
|
24
|
+
*
|
|
25
|
+
* Usage (src/pages/v1/mcp.ts):
|
|
26
|
+
* ```ts
|
|
27
|
+
* import { createMCPHandler } from '@corsenai/corsen-context-astro';
|
|
28
|
+
* import { siteProvider } from '../../lib/corsen-provider';
|
|
29
|
+
*
|
|
30
|
+
* export const { POST, OPTIONS } = createMCPHandler(
|
|
31
|
+
* { siteUrl: import.meta.env.SITE ?? 'https://example.com' },
|
|
32
|
+
* siteProvider,
|
|
33
|
+
* );
|
|
34
|
+
* ```
|
|
35
|
+
*/
|
|
36
|
+
declare function createMCPHandler(config: CorsenContextConfig, provider: ContentProvider, options?: HandlerOptions): {
|
|
37
|
+
POST: (context: AstroContext) => Promise<Response>;
|
|
38
|
+
OPTIONS: (context: AstroContext) => Promise<Response>;
|
|
39
|
+
};
|
|
40
|
+
/** Creates an Astro GET handler that serves /llms.txt. */
|
|
41
|
+
declare function createLlmsTxtHandler(config: CorsenContextConfig, provider: ContentProvider, options?: HandlerOptions): () => Promise<Response>;
|
|
42
|
+
/** Creates an Astro GET handler that serves /llms-full.txt. */
|
|
43
|
+
declare function createLlmsFullTxtHandler(config: CorsenContextConfig, provider: ContentProvider, options?: HandlerOptions): () => Promise<Response>;
|
|
44
|
+
|
|
45
|
+
export { type AstroContext, type HandlerOptions, createLlmsFullTxtHandler, createLlmsTxtHandler, createMCPHandler };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
|
|
20
|
+
// src/index.ts
|
|
21
|
+
var index_exports = {};
|
|
22
|
+
__export(index_exports, {
|
|
23
|
+
createLlmsFullTxtHandler: () => createLlmsFullTxtHandler,
|
|
24
|
+
createLlmsTxtHandler: () => createLlmsTxtHandler,
|
|
25
|
+
createMCPHandler: () => createMCPHandler
|
|
26
|
+
});
|
|
27
|
+
module.exports = __toCommonJS(index_exports);
|
|
28
|
+
|
|
29
|
+
// src/handlers.ts
|
|
30
|
+
var import_corsen_context = require("@corsenai/corsen-context");
|
|
31
|
+
var cachedInstances = /* @__PURE__ */ new WeakMap();
|
|
32
|
+
function getInstance(config, provider, cache) {
|
|
33
|
+
let providerInstances = cachedInstances.get(provider);
|
|
34
|
+
if (!providerInstances) {
|
|
35
|
+
providerInstances = /* @__PURE__ */ new Map();
|
|
36
|
+
cachedInstances.set(provider, providerInstances);
|
|
37
|
+
}
|
|
38
|
+
const configKey = stableStringify(config);
|
|
39
|
+
let instance = providerInstances.get(configKey);
|
|
40
|
+
if (!instance) {
|
|
41
|
+
instance = new import_corsen_context.CorsenContext(config, provider, cache);
|
|
42
|
+
providerInstances.set(configKey, instance);
|
|
43
|
+
}
|
|
44
|
+
return instance;
|
|
45
|
+
}
|
|
46
|
+
function stableStringify(value) {
|
|
47
|
+
if (value === null || typeof value !== "object") {
|
|
48
|
+
return JSON.stringify(value) ?? "undefined";
|
|
49
|
+
}
|
|
50
|
+
if (Array.isArray(value)) {
|
|
51
|
+
return `[${value.map((item) => stableStringify(item)).join(",")}]`;
|
|
52
|
+
}
|
|
53
|
+
const record = value;
|
|
54
|
+
return `{${Object.keys(record).sort().map((key) => `${JSON.stringify(key)}:${stableStringify(record[key])}`).join(",")}}`;
|
|
55
|
+
}
|
|
56
|
+
function getClientIp(context, trustProxy) {
|
|
57
|
+
if (trustProxy) {
|
|
58
|
+
const cfIp = context.request.headers.get("cf-connecting-ip");
|
|
59
|
+
if (cfIp) return cfIp.trim();
|
|
60
|
+
const realIp = context.request.headers.get("x-real-ip");
|
|
61
|
+
if (realIp) return realIp.trim();
|
|
62
|
+
const xff = context.request.headers.get("x-forwarded-for");
|
|
63
|
+
if (xff) {
|
|
64
|
+
const first = xff.split(",")[0]?.trim();
|
|
65
|
+
if (first) return first;
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
return context.clientAddress || "unknown";
|
|
69
|
+
}
|
|
70
|
+
function getApiKey(request) {
|
|
71
|
+
return request.headers.get("x-mcp-key") || request.headers.get("authorization")?.replace("Bearer ", "") || void 0;
|
|
72
|
+
}
|
|
73
|
+
async function readBoundedText(request) {
|
|
74
|
+
const body = request.body;
|
|
75
|
+
if (!body || typeof body.getReader !== "function") {
|
|
76
|
+
const text = await request.text();
|
|
77
|
+
return new TextEncoder().encode(text).length > import_corsen_context.MAX_BODY_SIZE ? null : text;
|
|
78
|
+
}
|
|
79
|
+
const reader = body.getReader();
|
|
80
|
+
const chunks = [];
|
|
81
|
+
let total = 0;
|
|
82
|
+
for (; ; ) {
|
|
83
|
+
const { done, value } = await reader.read();
|
|
84
|
+
if (done) break;
|
|
85
|
+
if (value) {
|
|
86
|
+
total += value.byteLength;
|
|
87
|
+
if (total > import_corsen_context.MAX_BODY_SIZE) {
|
|
88
|
+
await reader.cancel();
|
|
89
|
+
return null;
|
|
90
|
+
}
|
|
91
|
+
chunks.push(value);
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
const merged = new Uint8Array(total);
|
|
95
|
+
let offset = 0;
|
|
96
|
+
for (const chunk of chunks) {
|
|
97
|
+
merged.set(chunk, offset);
|
|
98
|
+
offset += chunk.byteLength;
|
|
99
|
+
}
|
|
100
|
+
return new TextDecoder().decode(merged);
|
|
101
|
+
}
|
|
102
|
+
function createMCPHandler(config, provider, options) {
|
|
103
|
+
const trustProxy = config.security?.trustProxy ?? false;
|
|
104
|
+
function createServer(instance) {
|
|
105
|
+
return instance.createMCPServer({
|
|
106
|
+
rateLimitStore: options?.rateLimitStore,
|
|
107
|
+
logger: options?.logger
|
|
108
|
+
});
|
|
109
|
+
}
|
|
110
|
+
async function POST(context) {
|
|
111
|
+
const { request } = context;
|
|
112
|
+
const instance = getInstance(config, provider, options?.cache);
|
|
113
|
+
const server = createServer(instance);
|
|
114
|
+
const headers = new Headers();
|
|
115
|
+
for (const [key, value] of Object.entries(server.getSecurityHeaders())) {
|
|
116
|
+
headers.set(key, value);
|
|
117
|
+
}
|
|
118
|
+
headers.set("Content-Type", "application/json");
|
|
119
|
+
const origin = request.headers.get("origin") || void 0;
|
|
120
|
+
for (const [key, value] of Object.entries(server.getCorsHeaders(origin))) {
|
|
121
|
+
headers.set(key, value);
|
|
122
|
+
}
|
|
123
|
+
const clientIp = getClientIp(context, trustProxy);
|
|
124
|
+
const apiKey = getApiKey(request);
|
|
125
|
+
const rateLimit = await server.checkRateLimit(clientIp, apiKey);
|
|
126
|
+
for (const [key, value] of Object.entries(rateLimit.headers)) {
|
|
127
|
+
headers.set(key, value);
|
|
128
|
+
}
|
|
129
|
+
if (!rateLimit.allowed) {
|
|
130
|
+
return new Response(
|
|
131
|
+
JSON.stringify({ jsonrpc: "2.0", error: { code: -32e3, message: "Rate limit exceeded" }, id: null }),
|
|
132
|
+
{ status: 429, headers }
|
|
133
|
+
);
|
|
134
|
+
}
|
|
135
|
+
if (!server.checkAuth(apiKey)) {
|
|
136
|
+
return new Response(
|
|
137
|
+
JSON.stringify({ jsonrpc: "2.0", error: { code: -32e3, message: "Unauthorized" }, id: null }),
|
|
138
|
+
{ status: 401, headers }
|
|
139
|
+
);
|
|
140
|
+
}
|
|
141
|
+
const raw = await readBoundedText(request);
|
|
142
|
+
if (raw === null) {
|
|
143
|
+
return new Response(
|
|
144
|
+
JSON.stringify({ jsonrpc: "2.0", error: { code: -32600, message: "Request body too large" }, id: null }),
|
|
145
|
+
{ status: 413, headers }
|
|
146
|
+
);
|
|
147
|
+
}
|
|
148
|
+
let body;
|
|
149
|
+
try {
|
|
150
|
+
body = JSON.parse(raw);
|
|
151
|
+
} catch {
|
|
152
|
+
return new Response(
|
|
153
|
+
JSON.stringify({ jsonrpc: "2.0", error: { code: -32700, message: "Parse error" }, id: null }),
|
|
154
|
+
{ status: 400, headers }
|
|
155
|
+
);
|
|
156
|
+
}
|
|
157
|
+
const result = await server.handleRequest(body, clientIp, apiKey, { skipRateLimit: true });
|
|
158
|
+
if (result === null) {
|
|
159
|
+
return new Response(null, { status: 204, headers });
|
|
160
|
+
}
|
|
161
|
+
return new Response(JSON.stringify(result), { status: 200, headers });
|
|
162
|
+
}
|
|
163
|
+
async function OPTIONS(context) {
|
|
164
|
+
const instance = getInstance(config, provider, options?.cache);
|
|
165
|
+
const server = createServer(instance);
|
|
166
|
+
const headers = new Headers();
|
|
167
|
+
for (const [key, value] of Object.entries(server.getSecurityHeaders())) {
|
|
168
|
+
headers.set(key, value);
|
|
169
|
+
}
|
|
170
|
+
const origin = context.request.headers.get("origin") || void 0;
|
|
171
|
+
for (const [key, value] of Object.entries(server.getCorsHeaders(origin))) {
|
|
172
|
+
headers.set(key, value);
|
|
173
|
+
}
|
|
174
|
+
return new Response(null, { status: 204, headers });
|
|
175
|
+
}
|
|
176
|
+
return { POST, OPTIONS };
|
|
177
|
+
}
|
|
178
|
+
function createLlmsTxtHandler(config, provider, options) {
|
|
179
|
+
return async function GET() {
|
|
180
|
+
const text = await getInstance(config, provider, options?.cache).generateLlmsTxt();
|
|
181
|
+
const headers = new Headers(import_corsen_context.SECURITY_HEADERS);
|
|
182
|
+
headers.set("Content-Type", "text/plain; charset=utf-8");
|
|
183
|
+
headers.set("Cache-Control", "public, max-age=3600, s-maxage=3600");
|
|
184
|
+
return new Response(text, { status: 200, headers });
|
|
185
|
+
};
|
|
186
|
+
}
|
|
187
|
+
function createLlmsFullTxtHandler(config, provider, options) {
|
|
188
|
+
return async function GET() {
|
|
189
|
+
const text = await getInstance(config, provider, options?.cache).generateLlmsFullTxt();
|
|
190
|
+
const headers = new Headers(import_corsen_context.SECURITY_HEADERS);
|
|
191
|
+
headers.set("Content-Type", "text/plain; charset=utf-8");
|
|
192
|
+
headers.set("Cache-Control", "public, max-age=3600, s-maxage=3600");
|
|
193
|
+
return new Response(text, { status: 200, headers });
|
|
194
|
+
};
|
|
195
|
+
}
|
|
196
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
197
|
+
0 && (module.exports = {
|
|
198
|
+
createLlmsFullTxtHandler,
|
|
199
|
+
createLlmsTxtHandler,
|
|
200
|
+
createMCPHandler
|
|
201
|
+
});
|
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
// src/handlers.ts
|
|
2
|
+
import {
|
|
3
|
+
CorsenContext,
|
|
4
|
+
MAX_BODY_SIZE,
|
|
5
|
+
SECURITY_HEADERS
|
|
6
|
+
} from "@corsenai/corsen-context";
|
|
7
|
+
var cachedInstances = /* @__PURE__ */ new WeakMap();
|
|
8
|
+
function getInstance(config, provider, cache) {
|
|
9
|
+
let providerInstances = cachedInstances.get(provider);
|
|
10
|
+
if (!providerInstances) {
|
|
11
|
+
providerInstances = /* @__PURE__ */ new Map();
|
|
12
|
+
cachedInstances.set(provider, providerInstances);
|
|
13
|
+
}
|
|
14
|
+
const configKey = stableStringify(config);
|
|
15
|
+
let instance = providerInstances.get(configKey);
|
|
16
|
+
if (!instance) {
|
|
17
|
+
instance = new CorsenContext(config, provider, cache);
|
|
18
|
+
providerInstances.set(configKey, instance);
|
|
19
|
+
}
|
|
20
|
+
return instance;
|
|
21
|
+
}
|
|
22
|
+
function stableStringify(value) {
|
|
23
|
+
if (value === null || typeof value !== "object") {
|
|
24
|
+
return JSON.stringify(value) ?? "undefined";
|
|
25
|
+
}
|
|
26
|
+
if (Array.isArray(value)) {
|
|
27
|
+
return `[${value.map((item) => stableStringify(item)).join(",")}]`;
|
|
28
|
+
}
|
|
29
|
+
const record = value;
|
|
30
|
+
return `{${Object.keys(record).sort().map((key) => `${JSON.stringify(key)}:${stableStringify(record[key])}`).join(",")}}`;
|
|
31
|
+
}
|
|
32
|
+
function getClientIp(context, trustProxy) {
|
|
33
|
+
if (trustProxy) {
|
|
34
|
+
const cfIp = context.request.headers.get("cf-connecting-ip");
|
|
35
|
+
if (cfIp) return cfIp.trim();
|
|
36
|
+
const realIp = context.request.headers.get("x-real-ip");
|
|
37
|
+
if (realIp) return realIp.trim();
|
|
38
|
+
const xff = context.request.headers.get("x-forwarded-for");
|
|
39
|
+
if (xff) {
|
|
40
|
+
const first = xff.split(",")[0]?.trim();
|
|
41
|
+
if (first) return first;
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
return context.clientAddress || "unknown";
|
|
45
|
+
}
|
|
46
|
+
function getApiKey(request) {
|
|
47
|
+
return request.headers.get("x-mcp-key") || request.headers.get("authorization")?.replace("Bearer ", "") || void 0;
|
|
48
|
+
}
|
|
49
|
+
async function readBoundedText(request) {
|
|
50
|
+
const body = request.body;
|
|
51
|
+
if (!body || typeof body.getReader !== "function") {
|
|
52
|
+
const text = await request.text();
|
|
53
|
+
return new TextEncoder().encode(text).length > MAX_BODY_SIZE ? null : text;
|
|
54
|
+
}
|
|
55
|
+
const reader = body.getReader();
|
|
56
|
+
const chunks = [];
|
|
57
|
+
let total = 0;
|
|
58
|
+
for (; ; ) {
|
|
59
|
+
const { done, value } = await reader.read();
|
|
60
|
+
if (done) break;
|
|
61
|
+
if (value) {
|
|
62
|
+
total += value.byteLength;
|
|
63
|
+
if (total > MAX_BODY_SIZE) {
|
|
64
|
+
await reader.cancel();
|
|
65
|
+
return null;
|
|
66
|
+
}
|
|
67
|
+
chunks.push(value);
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
const merged = new Uint8Array(total);
|
|
71
|
+
let offset = 0;
|
|
72
|
+
for (const chunk of chunks) {
|
|
73
|
+
merged.set(chunk, offset);
|
|
74
|
+
offset += chunk.byteLength;
|
|
75
|
+
}
|
|
76
|
+
return new TextDecoder().decode(merged);
|
|
77
|
+
}
|
|
78
|
+
function createMCPHandler(config, provider, options) {
|
|
79
|
+
const trustProxy = config.security?.trustProxy ?? false;
|
|
80
|
+
function createServer(instance) {
|
|
81
|
+
return instance.createMCPServer({
|
|
82
|
+
rateLimitStore: options?.rateLimitStore,
|
|
83
|
+
logger: options?.logger
|
|
84
|
+
});
|
|
85
|
+
}
|
|
86
|
+
async function POST(context) {
|
|
87
|
+
const { request } = context;
|
|
88
|
+
const instance = getInstance(config, provider, options?.cache);
|
|
89
|
+
const server = createServer(instance);
|
|
90
|
+
const headers = new Headers();
|
|
91
|
+
for (const [key, value] of Object.entries(server.getSecurityHeaders())) {
|
|
92
|
+
headers.set(key, value);
|
|
93
|
+
}
|
|
94
|
+
headers.set("Content-Type", "application/json");
|
|
95
|
+
const origin = request.headers.get("origin") || void 0;
|
|
96
|
+
for (const [key, value] of Object.entries(server.getCorsHeaders(origin))) {
|
|
97
|
+
headers.set(key, value);
|
|
98
|
+
}
|
|
99
|
+
const clientIp = getClientIp(context, trustProxy);
|
|
100
|
+
const apiKey = getApiKey(request);
|
|
101
|
+
const rateLimit = await server.checkRateLimit(clientIp, apiKey);
|
|
102
|
+
for (const [key, value] of Object.entries(rateLimit.headers)) {
|
|
103
|
+
headers.set(key, value);
|
|
104
|
+
}
|
|
105
|
+
if (!rateLimit.allowed) {
|
|
106
|
+
return new Response(
|
|
107
|
+
JSON.stringify({ jsonrpc: "2.0", error: { code: -32e3, message: "Rate limit exceeded" }, id: null }),
|
|
108
|
+
{ status: 429, headers }
|
|
109
|
+
);
|
|
110
|
+
}
|
|
111
|
+
if (!server.checkAuth(apiKey)) {
|
|
112
|
+
return new Response(
|
|
113
|
+
JSON.stringify({ jsonrpc: "2.0", error: { code: -32e3, message: "Unauthorized" }, id: null }),
|
|
114
|
+
{ status: 401, headers }
|
|
115
|
+
);
|
|
116
|
+
}
|
|
117
|
+
const raw = await readBoundedText(request);
|
|
118
|
+
if (raw === null) {
|
|
119
|
+
return new Response(
|
|
120
|
+
JSON.stringify({ jsonrpc: "2.0", error: { code: -32600, message: "Request body too large" }, id: null }),
|
|
121
|
+
{ status: 413, headers }
|
|
122
|
+
);
|
|
123
|
+
}
|
|
124
|
+
let body;
|
|
125
|
+
try {
|
|
126
|
+
body = JSON.parse(raw);
|
|
127
|
+
} catch {
|
|
128
|
+
return new Response(
|
|
129
|
+
JSON.stringify({ jsonrpc: "2.0", error: { code: -32700, message: "Parse error" }, id: null }),
|
|
130
|
+
{ status: 400, headers }
|
|
131
|
+
);
|
|
132
|
+
}
|
|
133
|
+
const result = await server.handleRequest(body, clientIp, apiKey, { skipRateLimit: true });
|
|
134
|
+
if (result === null) {
|
|
135
|
+
return new Response(null, { status: 204, headers });
|
|
136
|
+
}
|
|
137
|
+
return new Response(JSON.stringify(result), { status: 200, headers });
|
|
138
|
+
}
|
|
139
|
+
async function OPTIONS(context) {
|
|
140
|
+
const instance = getInstance(config, provider, options?.cache);
|
|
141
|
+
const server = createServer(instance);
|
|
142
|
+
const headers = new Headers();
|
|
143
|
+
for (const [key, value] of Object.entries(server.getSecurityHeaders())) {
|
|
144
|
+
headers.set(key, value);
|
|
145
|
+
}
|
|
146
|
+
const origin = context.request.headers.get("origin") || void 0;
|
|
147
|
+
for (const [key, value] of Object.entries(server.getCorsHeaders(origin))) {
|
|
148
|
+
headers.set(key, value);
|
|
149
|
+
}
|
|
150
|
+
return new Response(null, { status: 204, headers });
|
|
151
|
+
}
|
|
152
|
+
return { POST, OPTIONS };
|
|
153
|
+
}
|
|
154
|
+
function createLlmsTxtHandler(config, provider, options) {
|
|
155
|
+
return async function GET() {
|
|
156
|
+
const text = await getInstance(config, provider, options?.cache).generateLlmsTxt();
|
|
157
|
+
const headers = new Headers(SECURITY_HEADERS);
|
|
158
|
+
headers.set("Content-Type", "text/plain; charset=utf-8");
|
|
159
|
+
headers.set("Cache-Control", "public, max-age=3600, s-maxage=3600");
|
|
160
|
+
return new Response(text, { status: 200, headers });
|
|
161
|
+
};
|
|
162
|
+
}
|
|
163
|
+
function createLlmsFullTxtHandler(config, provider, options) {
|
|
164
|
+
return async function GET() {
|
|
165
|
+
const text = await getInstance(config, provider, options?.cache).generateLlmsFullTxt();
|
|
166
|
+
const headers = new Headers(SECURITY_HEADERS);
|
|
167
|
+
headers.set("Content-Type", "text/plain; charset=utf-8");
|
|
168
|
+
headers.set("Cache-Control", "public, max-age=3600, s-maxage=3600");
|
|
169
|
+
return new Response(text, { status: 200, headers });
|
|
170
|
+
};
|
|
171
|
+
}
|
|
172
|
+
export {
|
|
173
|
+
createLlmsFullTxtHandler,
|
|
174
|
+
createLlmsTxtHandler,
|
|
175
|
+
createMCPHandler
|
|
176
|
+
};
|
package/package.json
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@corsenai/corsen-context-astro",
|
|
3
|
+
"version": "1.2.0",
|
|
4
|
+
"description": "Astro adapter for Corsen Context — AI Context Layer with MCP + llms.txt",
|
|
5
|
+
"author": "Corsen AI <contact@corsen.ai>",
|
|
6
|
+
"license": "MIT",
|
|
7
|
+
"homepage": "https://github.com/CorsenAI/corsen-context",
|
|
8
|
+
"repository": {
|
|
9
|
+
"type": "git",
|
|
10
|
+
"url": "https://github.com/CorsenAI/corsen-context.git",
|
|
11
|
+
"directory": "packages/astro-adapter"
|
|
12
|
+
},
|
|
13
|
+
"keywords": [
|
|
14
|
+
"mcp",
|
|
15
|
+
"llms-txt",
|
|
16
|
+
"astro",
|
|
17
|
+
"ai",
|
|
18
|
+
"corsen"
|
|
19
|
+
],
|
|
20
|
+
"main": "./dist/index.js",
|
|
21
|
+
"module": "./dist/index.mjs",
|
|
22
|
+
"types": "./dist/index.d.ts",
|
|
23
|
+
"exports": {
|
|
24
|
+
".": {
|
|
25
|
+
"types": "./dist/index.d.ts",
|
|
26
|
+
"import": "./dist/index.mjs",
|
|
27
|
+
"require": "./dist/index.js"
|
|
28
|
+
}
|
|
29
|
+
},
|
|
30
|
+
"files": [
|
|
31
|
+
"dist",
|
|
32
|
+
"LICENSE",
|
|
33
|
+
"README.md"
|
|
34
|
+
],
|
|
35
|
+
"dependencies": {
|
|
36
|
+
"@corsenai/corsen-context": "1.2.0"
|
|
37
|
+
},
|
|
38
|
+
"devDependencies": {
|
|
39
|
+
"@types/node": "^22.0.0",
|
|
40
|
+
"tsup": "^8.3.0",
|
|
41
|
+
"typescript": "^5.7.0",
|
|
42
|
+
"vitest": "^2.1.0"
|
|
43
|
+
},
|
|
44
|
+
"publishConfig": {
|
|
45
|
+
"access": "public"
|
|
46
|
+
},
|
|
47
|
+
"bugs": {
|
|
48
|
+
"url": "https://github.com/CorsenAI/corsen-context/issues"
|
|
49
|
+
},
|
|
50
|
+
"sideEffects": false,
|
|
51
|
+
"engines": {
|
|
52
|
+
"node": ">=18.0.0"
|
|
53
|
+
},
|
|
54
|
+
"scripts": {
|
|
55
|
+
"build": "tsup src/index.ts --format cjs,esm --dts --clean",
|
|
56
|
+
"test": "vitest run",
|
|
57
|
+
"typecheck": "tsc --noEmit",
|
|
58
|
+
"clean": "rm -rf dist"
|
|
59
|
+
}
|
|
60
|
+
}
|