@kya-os/mcp-i
Version:
The TypeScript MCP framework with identity features built-in
59 lines (58 loc) • 1.63 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.createContext = createContext;
const async_hooks_1 = require("async_hooks");
const setGlobalContext = (key, context) => {
globalThis[key] = context;
};
const getGlobalContext = (key) => {
return globalThis[key];
};
/**
* Create context allows you to create scoped variables for fucntions.
* Similar to React's context API.
* Usage:
* ```ts
* interface MyContext {
* value: string;
* }
*
* const context = createContext({ name: "my-context" });
*
* context.provider({
* value: "hello",
* }, () => {
* // Do something with the context
* })```
*/
function createContext({ name, }) {
const storageKey = Symbol.for(`xmcp-context-${name}`);
if (getGlobalContext(storageKey)) {
return getGlobalContext(storageKey);
}
const context = new async_hooks_1.AsyncLocalStorage();
const getContext = () => {
const store = context.getStore();
if (!store) {
throw new Error(`getContext() can only be used within the ${name} context.`);
}
return store;
};
const setContext = (data) => {
const store = context.getStore();
if (!store) {
throw new Error(`setContext() can only be used within the ${name} context.`);
}
Object.assign(store, data);
};
const provider = (initialValue, callback) => {
return context.run(initialValue, callback);
};
const result = {
provider,
getContext,
setContext,
};
setGlobalContext(storageKey, result);
return result;
}