quadratic-mcpmain.ts1 match
5152// ---------- Handler ----------
53export default async function (req: Request): Promise<Response> {
54// Handle CORS preflight requests
55if (req.method === "OPTIONS") {
untitled-9994upload.ts1 match
111213export default async function (req: Request): Promise<Response> {
14const searchParams = new URL(req.url).searchParams
15const gig = searchParams.get("gig")
1export default function () {
2const body = `<!doctype html>
3<html lang="en">
101102/************************************************************************
103* State: raw variables & functions, and evaluated variables
104************************************************************************/
105const rawVars = new Map(); // name -> rhs string (raw)
106const functions = new Map(); // name -> { params: [], body: "..." }
107const computedVars = new Map(); // name -> evaluated value (primitive, array, string, etc)
108110* Helpers
111************************************************************************/
112function isQuotedString(s) {
113return (s.length >= 2) && ((s[0] === '"' && s[s.length-1] === '"') || (s[0] === "'" && s[s.length-1] === "'"));
114}
115116function toObj(map) {
117const o = Object.create(null);
118for (const [k,v] of map.entries()) o[k] = v;
120}
121
122function parseRange(s) {
123const m = s.match(/(\\d+(?:\\.\\d+)?)\\s*(am|pm)?\\s*[\\โ\\-]\\s*(\\d+(?:\\.\\d+)?)\\s*(am|pm)?/i);
124if (!m) return Number(s); // fallback if plain number
149// Evaluate an expression string in a sandbox that includes:
150// - current computedVars
151// - user functions (as JS functions that evaluate their bodies with the same sandbox + parameters)
152// - builtins
153// - automatic range parsing
154function evalWithScope(expr) {
155// First, replace any range patterns with their numeric values
156const processedExpr = expr.replace(/(\\d+(?:\\.\\d+)?)\\s*(am|pm)?\\s*[\\โ\\-]\\s*(\\d+(?:\\.\\d+)?)\\s*(am|pm)?/gi, (match) => {
159160const scope = Object.assign({}, builtins, toObj(computedVars));
161for (const [name, def] of functions.entries()) {
162scope[name] = (...args) => {
163const local = Object.assign({}, scope);
164def.params.forEach((p, i) => { local[p] = args[i]; });
165return Function('scope','with(scope){return ('+def.body+')}')(local);
166};
167}
168
169try {
170let val = Function('scope','with(scope){return ('+processedExpr+')}')(scope);
171return val;
172} catch (e) { throw e; }
175/************************************************************************
176* Parse the document top-down:
177* - function defs f(a,b)=...
178* - variable defs name = rhs (rhs may be quoted string OR an expression)
179*
180* We evaluate variables in document order so earlier defs are available to later ones.
181************************************************************************/
182function parseDocument(doc) {
183rawVars.clear();
184functions.clear();
185computedVars.clear();
186190if (!line) continue;
191192// function: name(arg1, arg2) = body
193const fm = line.match(/^([A-Za-z_][\\w]*)\\s*\\(([^)]*)\\)\\s*=\\s*(.+)$/);
194if (fm) {
196const params = fm[2].split(',').map(s=>s.trim()).filter(Boolean);
197const body = fm[3].trim();
198functions.set(name, { params, body });
199continue;
200}
207rawVars.set(name, rhs);
208209// attempt to evaluate using current environment (earlier vars + functions)
210try {
211let value;
314}, { decorations: v => v.decorations });
315316function stringifyValue(v) {
317if (v === null || v === undefined) return String(v);
318if (typeof v === 'number') {
val-town-http-mcp-servervtCli.ts9 matches
8* @returns Promise resolving to boolean indicating CLI availability
9*/
10export async function isVtCliAvailable(): Promise<boolean> {
11try {
12const command = new Deno.Command("which", {
30* @returns Promise resolving to boolean indicating CLI availability
31*/
32export async function getCliAvailability(): Promise<boolean> {
33if (_isCliAvailable === null) {
34_isCliAvailable = await isVtCliAvailable();
42* @returns Promise resolving to an object containing command execution result
43*/
44export async function runVtCommand(args: string[]): Promise<{
45success: boolean;
46output: string;
7172/**
73* Parse CLI JSON output (placeholder for missing function)
74* @param output CLI output string to parse
75* @returns Parsed JSON object or error
76*/
77export function parseCliJsonOutput(output: string): any {
78try {
79return JSON.parse(output);
8485/**
86* Prepare Val workspace (placeholder for missing function)
87* @param valId Val ID to prepare workspace for
88* @returns Workspace preparation result
89*/
90export async function prepareValWorkspace(valId: string): Promise<{
91success: boolean;
92workspacePath?: string;
102103/**
104* Cleanup temporary directory (placeholder for missing function)
105* @param dirPath Directory path to cleanup
106* @returns Cleanup result
107*/
108export async function cleanupTempDirectory(dirPath: string): Promise<{
109success: boolean;
110error?: string;
6import {z} from "npm:zod"
78export function registerValTools(server: McpServer, config: Config) {
9// Get val by username and val name
10server.tool(
val-town-http-mcp-servervalley.txt11 matches
10- **Never bake in secrets into the code** - always use environment variables
11- Include comments explaining complex logic (avoid commenting obvious operations)
12- Follow modern ES6+ conventions and functional programming practices if possible
1314## Types of triggers
2122```ts
23export default async function (req: Request) {
24return new Response("Hello World");
25}
3536```ts
37export default async function () {
38// Scheduled task code
39}
4950```ts
51export default async function (email: Email) {
52// Process email
53}
58## Val Town Standard Libraries
5960Val Town provides several hosted services and utility functions.
6162### Blob Storage
112```
113114## Val Town Utility Functions
115116Val Town provides several utility functions to help with common project tasks.
117118### Importing Utilities
191โ โโโ database/
192โ โ โโโ migrations.ts # Schema definitions
193โ โ โโโ queries.ts # DB query functions
194โ โ โโโ README.md
195โ โโโ routes/ # Route modules
210โโโ shared/
211โโโ README.md
212โโโ utils.ts # Shared types and functions
213```
214217- Hono is the recommended API framework
218- Main entry point should be `backend/index.ts`
219- **Static asset serving:** Use the utility functions to read and serve project files:
220```ts
221import { readFile, serveFile } from "https://esm.town/v/std/utils@85-main/index.ts";
251- Run migrations on startup or comment out for performance
252- Change table names when modifying schemas rather than altering
253- Export clear query functions with proper TypeScript typing
254255## Common Gotchas and Solutions
6## Understanding Val Town
78Val Town is a platform for writing, running, and deploying JavaScript/TypeScript code in the cloud. It functions as a social coding environment where users can create and share code that runs on Val Town's serverless infrastructure.
910### Val Town Projects
21## Core Guidelines
2223- Provide complete, functional solutions
24- Test logic against edge cases
25- Follow Val Town's platform requirements
26- Write clean, maintainable TypeScript/TSX code
27- Add appropriate TypeScript types for all data structures
28- Prefer functional programming practices where appropriate
2930## Coding Requirements
5import {getErrorMessage} from "../lib/errorUtils.ts"
67export function registerUserTools(server: McpServer, config: Config) {
8// Get user information by username
9server.tool(
val-town-http-mcp-servertownie.txt17 matches
101. `http`: http vals export a default server request handler.
112. `script`: script vals can be imported into other vals, similar to an npm package.
123. `cron`: cron vals export a function that can automatically run at user-set intervals, similar to a cron command.
134. `email`: email vals export a function that runs when its associated email address receives an email.
1415Follow these requirements for Val Town when generating code.
49</requirements>
5051If the user asks for specific functionality, the Val Town standard library includes the following:
5253<libraries>
63```
6465Blob storage only works on the server. If the val includes client-side code, use dynamic imports to import this module in the server function, e.g.:
66`const { blob } = await import("https://esm.town/v/std/blob");`
67</library>
78If you are changing a SQLite table's schema, you should also change the table's name so it creates a fresh table, ie by adding _2 or _3 after it everywhere. Ensure that tables are created before they are used.
7980SQLite storage only works on the server. If the val includes client-side code, use dynamic imports to import this module in the server function, e.g.:
81`const { sqlite } = await import("https://esm.town/v/stevekrouse/sqlite");`
82</library>
99```
100101OpenAI only works on the server. If the val includes client-side code, use dynamic imports to import this module in the server function, e.g.:
102`const { OpenAI } = await import "https://esm.town/v/std/openai");`
103</library>
113```
114115Email only works on the server. If the val includes client-side code, use dynamic imports to import this module in the server function, e.g.:
116`const { email } = await import "https://esm.town/v/std/email");`
117</library>
131Write the code in ```val code fences.
132Include the val type as metadata on the code fence, e.g.: ```val type=script
133If this is a new val, decide what val type is appropriate based on the user's prompt. Default to choosing http type vals unless the user has requested specific functionality that requires a different type.
134135* If the user requests diff format in their prompt, follow these steps:
157* Use fetch to communicate with the backend server portion.
158*/
159function App() {
160return (
161<div>
167/**
168* Client-only code
169* Any code that makes use of document or window should be scoped to the `client()` function.
170* This val should not cause errors when imported as a module in a browser.
171*/
172function client() {
173createRoot(document.getElementById("root")).render(<App />);
174}
177/**
178* Server-only code
179* Any code that is meant to run on the server should be included in the server function.
180* This can include endpoints that the client side component can send fetch requests to.
181*/
182export default async function server(request: Request): Promise<Response> {
183/** If needed, blob storage or sqlite can be imported as a dynamic import in this function.
184* Blob storage should never be used in the browser directly.
185* Other server-side specific modules can be imported in a similar way.
232```val type=script
233/** Use this template for creating script vals only */
234export default function () {
235return "Hello, world";
236}
243```val type=cron
244/** Use this template for creating cron vals only */
245export default async function (interval: Interval) {
246// code will run at an interval set by the user
247console.log(`Hello, world: ${Date.now()}`);
270// The email address for this val will be `<username>.<valname>@valtown.email` which can be derived from:
271// const emailAddress = new URL(import.meta.url).pathname.split("/").slice(-2).join(".") + "@valtown.email";
272export default async function (e: Email) {
273console.log("Email received!", email.from, email.subject, email.text);
274}
5import {getErrorMessage} from "../lib/errorUtils.ts"
67export function registerSqliteTools(server: McpServer, config: Config) {
8// Execute SQL
9server.tool(
64)
6566// Fix for sqlite-query function
67server.tool(
68"sqlite-query",
91)
9293// Fix for sqlite-exec function
94server.tool(
95"sqlite-exec",