te.js 2.0.0 → 2.0.3

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 CHANGED
@@ -16,6 +16,7 @@
16
16
 
17
17
  <p align="center">
18
18
  <a href="https://tejas-documentation.vercel.app">Documentation</a> •
19
+ <a href="#ai-assisted-setup-mcp">AI Setup (MCP)</a> •
19
20
  <a href="#quick-start">Quick Start</a> •
20
21
  <a href="#features">Features</a> •
21
22
  <a href="./docs">Full Docs</a>
@@ -42,6 +43,7 @@ app.takeoff();
42
43
 
43
44
  ## Features
44
45
 
46
+ - **AI-Native (MCP)** — Ship with an MCP server so AI assistants can scaffold projects, generate routes, and write correct code with full framework knowledge
45
47
  - **Simple Routing** — Clean, method-agnostic URL structures with parameterized routes
46
48
  - **Express Compatible** — Use existing Express middleware alongside Tejas middleware
47
49
  - **Zero-Config Error Handling** — No try-catch needed! Tejas catches all errors automatically
@@ -53,6 +55,29 @@ app.takeoff();
53
55
  - **Auto-Discovery** — Automatic route registration from `.target.js` files
54
56
  - **Request Logging** — Built-in HTTP request and exception logging
55
57
 
58
+ ## AI-Assisted Setup (MCP)
59
+
60
+ > **Recommended** — The best way to get started with Tejas in the age of AI.
61
+
62
+ The [Tejas MCP server](https://www.npmjs.com/package/tejas-mcp) gives your IDE's AI assistant full knowledge of the framework — documentation, code examples, and purpose-built tools to scaffold projects and generate correct code. No more hallucinated APIs.
63
+
64
+ **Cursor** — add this to `.cursor/mcp.json`:
65
+
66
+ ```json
67
+ {
68
+ "mcpServers": {
69
+ "tejas": {
70
+ "command": "npx",
71
+ "args": ["-y", "tejas-mcp"]
72
+ }
73
+ }
74
+ }
75
+ ```
76
+
77
+ **Other MCP-compatible IDEs** — run `npx tejas-mcp` as the server command (stdio transport, no config needed).
78
+
79
+ Once connected, prompt your AI with things like *"Scaffold a new te.js project called my-api"* or *"Create a REST API with user CRUD routes"* — the assistant will generate framework-correct code using real te.js patterns.
80
+
56
81
  ## Quick Start
57
82
 
58
83
  ### Install
package/docs/README.md CHANGED
@@ -6,7 +6,7 @@ Welcome to the documentation for **Tejas** — a Node.js framework for building
6
6
 
7
7
  ### Getting Started
8
8
 
9
- - [Introduction & Quick Start](./getting-started.md) — Install, create your first app, and core concepts
9
+ - [Introduction & Quick Start](./getting-started.md) — AI-assisted setup (MCP), install, create your first app, and core concepts
10
10
  - [Configuration](./configuration.md) — Config sources, all available options, and environment variables
11
11
 
12
12
  ### Core Concepts
@@ -4,11 +4,45 @@ Tejas is a lightweight Node.js framework for building powerful backend services.
4
4
 
5
5
  ## Why Tejas?
6
6
 
7
+ - **AI-Native** — MCP server gives your AI assistant full framework knowledge for correct code generation
7
8
  - **Zero-Config Error Handling** — No try-catch needed! Tejas catches all errors automatically
8
9
  - **Clean, Readable Code** — Aviation-inspired naming makes code self-documenting
9
10
  - **Express Compatible** — Use your existing Express middleware
10
11
  - **Built-in Features** — Rate limiting, file uploads, database connections out of the box
11
12
 
13
+ ## AI-Assisted Setup (MCP) — Recommended
14
+
15
+ The fastest way to start building with Tejas is through your AI assistant. The **Tejas MCP server** (`tejas-mcp`) gives AI tools full access to framework documentation, validated code examples, and purpose-built tools that scaffold projects and generate correct te.js code.
16
+
17
+ ### Setup
18
+
19
+ **Cursor** — create or edit `.cursor/mcp.json` in your workspace:
20
+
21
+ ```json
22
+ {
23
+ "mcpServers": {
24
+ "tejas": {
25
+ "command": "npx",
26
+ "args": ["-y", "tejas-mcp"]
27
+ }
28
+ }
29
+ }
30
+ ```
31
+
32
+ **Other MCP-compatible IDEs** — run `npx tejas-mcp` as the stdio server command. No API keys required.
33
+
34
+ ### What you can do
35
+
36
+ Once connected, prompt your assistant naturally:
37
+
38
+ - *"Scaffold a new te.js project called my-api on port 5000"*
39
+ - *"Create a REST API with user CRUD routes using te.js"*
40
+ - *"Add a /health endpoint that returns system uptime"*
41
+
42
+ The MCP server provides these tools: `scaffold_project`, `generate_target`, `generate_app_entry`, `generate_config`, `get_documentation`, and `search_docs`.
43
+
44
+ ---
45
+
12
46
  ## Prerequisites
13
47
 
14
48
  - Node.js 18.x or higher
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "te.js",
3
- "version": "2.0.0",
3
+ "version": "2.0.3",
4
4
  "description": "A nodejs framework",
5
5
  "type": "module",
6
6
  "main": "te.js",
@@ -25,8 +25,19 @@
25
25
  },
26
26
  "repository": {
27
27
  "type": "git",
28
- "url": "git@github.com:hirakchhatbar/te.js.git"
28
+ "url": "git+ssh://git@github.com/hirakchhatbar/te.js.git"
29
29
  },
30
+ "files": [
31
+ "te.js",
32
+ "cli",
33
+ "server",
34
+ "database",
35
+ "rate-limit",
36
+ "utils",
37
+ "auto-docs",
38
+ "README.md",
39
+ "docs"
40
+ ],
30
41
  "dependencies": {
31
42
  "ansi-colors": "^4.1.3",
32
43
  "filesize": "^10.1.1",
@@ -1,234 +0,0 @@
1
- ---
2
- name: AI Native Framework Features
3
- overview: 'A framework that uses AI/LLM internally for its own features—not to expose LLM calls to developers, but to make the framework itself smarter: intelligent error handling, semantic routing, auto-documentation, self-optimization, and more.'
4
- todos: []
5
- isProject: false
6
- ---
7
-
8
- # AI-Native Framework: Internal AI Features
9
-
10
- ## What "AI Internally" Means
11
-
12
- **Not:** A framework that lets developers call LLMs (`ammo.llm()`, chat endpoints, etc.)
13
-
14
- **Yes:** A framework that **uses AI internally** to enhance its own capabilities. The framework itself is smarter—routing, errors, config, docs, and observability are powered by AI behind the scenes.
15
-
16
- ---
17
-
18
- ## Pain Points a Framework Can Solve by Using AI Internally
19
-
20
- ### 1. Useless Error Messages
21
-
22
- **Pain:** "Cannot read property 'id' of undefined" — developer spends 20 minutes tracing where it came from.
23
-
24
- **AI internally:** Framework catches the error, uses AI to analyze stack trace + request context + code, returns a **plain-language explanation** and **suggested fix** in the response or logs.
25
-
26
- ```
27
- Error: User lookup failed in GET /users/:id
28
- Cause: ammo.payload.id is undefined when id is "undefined" (string from query)
29
- Fix: Validate route param before use: if (!ammo.payload.id) ammo.notFound();
30
- ```
31
-
32
- ### 2. Routing is Rigid
33
-
34
- **Pain:** URLs must match exactly. Typos, alternate phrasings, or semantic equivalents (e.g. "user" vs "account") hit 404.
35
-
36
- **AI internally:** **Semantic routing** — framework uses embeddings + intent matching to route requests to the right handler even when the path doesn't match literally. "Get my account info" could route to `/users/:id` when confidence is high. Low confidence → 404 or clarification.
37
-
38
- ### 3. Documentation is Always Stale
39
-
40
- **Pain:** Docs drift from code. New routes, changed params, deprecated endpoints—docs don't reflect reality.
41
-
42
- **AI internally:** Framework **auto-generates docs** from registered targets, handlers, and schemas. On startup or via CLI, it produces OpenAPI/JSON Schema. When code changes, docs update. Optional: natural language descriptions from JSDoc/comments.
43
-
44
- ### 4. Configuration is Guesswork
45
-
46
- **Pain:** "What rate limit should I use?" "What body size?" Developers copy-paste from examples or guess.
47
-
48
- **AI internally:** **Natural language config** — "I want to handle 1000 req/min with strict rate limiting" → framework uses AI to suggest `maxRequests: 1000`, `algorithm: 'token-bucket'`, etc. Or: **self-tuning** — framework observes traffic, suggests config changes (e.g. "Consider increasing BODY_MAX_SIZE based on observed payloads").
49
-
50
- ### 5. Debugging is Manual Correlation
51
-
52
- **Pain:** Logs, traces, and errors are scattered. Developer manually correlates "this 500 at 3:42pm" with "this Redis timeout at 3:41pm."
53
-
54
- **AI internally:** **AI-powered root cause analysis** — framework aggregates logs, traces, and metrics; uses AI to suggest "Likely cause: Redis connection dropped. See trace X. Suggested fix: check Redis URL and retry logic."
55
-
56
- ### 6. Malformed Input = Generic 400
57
-
58
- **Pain:** Client sends `{ "name": 123 }` instead of `{ "name": "string" }`. Framework returns "Bad Request" with no guidance.
59
-
60
- **AI internally:** **Intelligent validation errors** — AI suggests what the client likely meant: "Field 'name' expected string, got number. Did you mean to send a string? Example: { name: John }."
61
-
62
- ### 7. Recovery Requires Humans
63
-
64
- **Pain:** Rate limit hit, DB timeout, or transient failure → 503. Human must retry or investigate.
65
-
66
- **AI internally:** **Auto-remediation** — framework can attempt retries with backoff, fallback to cached response, or route to a degraded handler. Optional: "This looks like a transient DB error; retrying in 2s" and auto-retry before returning 503.
67
-
68
- ### 8. Security is Reactive
69
-
70
- **Pain:** Unusual traffic patterns (DDoS, scraping, abuse) are detected only after damage.
71
-
72
- **AI internally:** **Anomaly detection** — framework uses ML/AI on request patterns (IP, path, frequency, payload size) to flag anomalies. Can auto-trigger stricter rate limits, CAPTCHA, or alerting.
73
-
74
- ---
75
-
76
- ## Recommended Internal AI Features for Tejas
77
-
78
- ### Tier 1: High Impact, Clear Value
79
-
80
- 1. **Intelligent Error Responses**
81
-
82
- - When `errorHandler` catches an error, optionally call AI with: stack trace, `ammo` context (path, method, payload keys), recent logs
83
- - AI returns: human-readable cause, suggested fix, relevant doc link
84
- - Attach to `LOG_EXCEPTIONS` output or optional `X-Error-Hint` header (dev only)
85
- - Location: extend [server/handler.js](server/handler.js) `errorHandler`, new `utils/ai-error-analyzer.js`
86
-
87
- 1. **Semantic Routing (Optional Mode)**
88
-
89
- - When exact `aim()` match fails, optionally use embeddings + intent registry to find best-matching target
90
- - Each target can declare: `intents: ["get user", "fetch account", "user profile"]`
91
- - Low confidence → fall through to 404
92
- - Requires: embedding provider (OpenAI, local model), intent index
93
- - Location: extend [server/targets/registry.js](server/targets/registry.js), new `server/targets/semantic-router.js`
94
-
95
- 1. **Auto-Generated Documentation**
96
-
97
- - CLI or startup hook: `tejas docs` or `app.withAutoDocs()`
98
- - Scans `targetRegistry.getAllEndpoints()`, infers schemas from handler patterns or explicit annotations
99
- - Outputs OpenAPI spec, or serves `/docs` with interactive UI
100
- - Optional: AI enhances descriptions from JSDoc
101
- - Location: new `utils/auto-docs.js`, optional `docs/` route
102
-
103
- ### Tier 2: Developer Experience
104
-
105
- 1. **Natural Language Config**
106
-
107
- - `app.configure("I need strict rate limiting for 500 req/min and 5MB body limit")`
108
- - AI parses intent, returns config object; user can approve or edit
109
- - Or: interactive `tejas init` that asks in plain language and generates `tejas.config.json`
110
- - Location: new `utils/ai-config.js`, CLI
111
-
112
- 1. **Smart Validation Errors**
113
-
114
- - When body-parser or validation fails, AI suggests corrections: "Expected 'email' as string; received number. Did you mean to send a string?"
115
- - Integrates with existing body parsing in [server/ammo/body-parser.js](server/ammo/body-parser.js)
116
- - Location: extend body-parser error path, new `utils/ai-validation-hint.js`
117
-
118
- 1. **Root Cause Analysis (Observability)**
119
-
120
- - When `LOG_EXCEPTIONS` is on, batch recent logs and send to AI for correlation
121
- - "Last 5 errors: Redis timeout, Redis timeout, DB connection refused. Likely cause: database connectivity. Check Redis URL."
122
- - Can run as background job or on-demand via admin endpoint
123
- - Location: new `utils/ai-rca.js`, optional admin target
124
-
125
- ### Tier 3: Advanced / Later
126
-
127
- 1. **Auto-Remediation**
128
-
129
- - Configurable: on 503/timeout, framework retries N times with backoff before returning
130
- - Or: fallback to cached/stale response when available
131
- - Requires policy: "when X, do Y"
132
- - Location: middleware or handler wrapper
133
-
134
- 1. **Anomaly Detection**
135
-
136
- - Framework tracks request patterns; ML model (or rules) flags anomalies
137
- - Triggers: alert, stricter rate limit, CAPTCHA challenge
138
- - Heavier dependency; may be plugin
139
- - Location: new `middlewares/anomaly-detector.js` (optional)
140
-
141
- ---
142
-
143
- ## Architecture: AI as Internal Service
144
-
145
- ```mermaid
146
- flowchart TB
147
- subgraph Request [Normal Request Flow]
148
- Req[HTTP Request]
149
- Handler[handler.js]
150
- Ammo[Ammo]
151
- Registry[TargetRegistry]
152
- end
153
-
154
- subgraph AI [AI Internal Services]
155
- ErrorAnalyzer[Error Analyzer]
156
- SemanticRouter[Semantic Router]
157
- ConfigGen[Config Generator]
158
- DocGen[Doc Generator]
159
- RCA[Root Cause Analysis]
160
- end
161
-
162
- Req --> Registry
163
- Registry -->|"exact match"| Handler
164
- Registry -->|"no match"| SemanticRouter
165
- SemanticRouter -->|"high confidence"| Handler
166
- SemanticRouter -->|"low confidence"| NotFound[404]
167
-
168
- Handler --> Ammo
169
- Ammo --> Response[Response]
170
-
171
- Handler -->|"throws"| ErrorAnalyzer
172
- ErrorAnalyzer -->|"enriched error"| Logs[Logs / X-Error-Hint]
173
-
174
- subgraph Dev [Dev / CLI]
175
- Init[tejas init]
176
- Docs[tejas docs]
177
- Init --> ConfigGen
178
- Docs --> DocGen
179
- end
180
- ```
181
-
182
- **Design principle:** AI is **opt-in** and **configurable**. Each feature can be disabled. AI calls happen in the framework's own code paths, not in user handlers.
183
-
184
- ---
185
-
186
- ## Implementation Considerations
187
-
188
- ### When to Call AI
189
-
190
- - **Synchronous (blocking):** Error analysis, validation hints — adds latency. Make it opt-in, async where possible (e.g. log enrichment in background).
191
- - **Asynchronous (non-blocking):** Doc generation, config suggestion, RCA — run on CLI or cron, not per-request.
192
-
193
- ### Cost and Latency
194
-
195
- - Every AI call costs money and adds latency. Features should be:
196
- - **Dev-only** where possible (error hints, config gen)
197
- - **Cached** (semantic route index, intent embeddings)
198
- - **Batchable** (RCA over last N errors, not per error)
199
-
200
- ### Provider Abstraction
201
-
202
- - Framework needs one AI provider interface: `analyzeError(context)`, `matchIntent(query, intents)`, `suggestConfig(nl)`, etc.
203
- - Pluggable: OpenAI, Anthropic, local Ollama, or disabled
204
- - Config: `app.withAI({ provider: 'openai', apiKey: env('OPENAI_API_KEY'), features: ['errorAnalysis', 'semanticRouting'] })`
205
-
206
- ### Privacy and Security
207
-
208
- - Never send sensitive data (tokens, passwords, PII) to AI without user consent
209
- - Error analysis: sanitize stack traces, redact payload values
210
- - Semantic routing: only path/headers, not body
211
-
212
- ---
213
-
214
- ## Summary: Pain Points Solved by Internal AI
215
-
216
- | Pain Point | Internal AI Feature | User-Visible Benefit |
217
- | ------------------------- | -------------------------- | ------------------------------------ |
218
- | Useless errors | Intelligent error analysis | Plain-language cause + suggested fix |
219
- | Rigid routing | Semantic routing | Intent-based matching, fewer 404s |
220
- | Stale docs | Auto-generated docs | Always-in-sync OpenAPI, `/docs` |
221
- | Config guesswork | Natural language config | "I need X" → suggested config |
222
- | Manual debugging | Root cause analysis | Correlated insights from logs |
223
- | Generic validation errors | Smart validation hints | "Did you mean...?" suggestions |
224
- | Human-only recovery | Auto-remediation | Retries, fallbacks, degraded mode |
225
- | Reactive security | Anomaly detection | Proactive abuse detection |
226
-
227
- ---
228
-
229
- ## Next Steps (When Implementing)
230
-
231
- 1. **Error analysis** — highest impact, dev-only, no user code changes. Add `withAI({ features: ['errorAnalysis'] })`.
232
- 2. **Auto-docs** — no AI required for v1 (static from registry); add AI-enhanced descriptions later.
233
- 3. **Semantic routing** — requires intent registry and embeddings; good for apps with many similar routes.
234
- 4. **Natural language config** — CLI-only, great for `tejas init` experience.