Repository navigation
Expand file tree
/
Copy pathfunction.go
More file actions
511 lines (468 loc) · 21.2 KB
/
Copy pathfunction.go
File metadata and controls
511 lines (468 loc) · 21.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
package blaxel
import (
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"net/url"
"slices"
"github.com/blaxel-ai/sdk-go/internal/apijson"
"github.com/blaxel-ai/sdk-go/internal/apiquery"
shimjson "github.com/blaxel-ai/sdk-go/internal/encoding/json"
"github.com/blaxel-ai/sdk-go/internal/requestconfig"
"github.com/blaxel-ai/sdk-go/option"
"github.com/blaxel-ai/sdk-go/packages/pagination"
"github.com/blaxel-ai/sdk-go/packages/param"
"github.com/blaxel-ai/sdk-go/packages/respjson"
"github.com/blaxel-ai/sdk-go/shared"
)
// FunctionService contains methods and other services that help with interacting
// with the blaxel API.
//
// Note, unlike clients, this service does not read variables from the environment
// automatically. You should not instantiate this service directly, and instead use
// the [NewFunctionService] method instead.
type FunctionService struct {
Options []option.RequestOption
}
// NewFunctionService generates a new service that applies the given options to
// each request. These options are applied after the parent client's options (if
// there is one), and before any request-specific options.
func NewFunctionService(opts ...option.RequestOption) (r FunctionService) {
r = FunctionService{}
r.Options = opts
return
}
// Creates a new MCP server function deployment. The function will expose tools via
// the Model Context Protocol that can be used by AI agents. Supports streamable
// HTTP transport.
func (r *FunctionService) New(ctx context.Context, body FunctionNewParams, opts ...option.RequestOption) (res *Function, err error) {
opts = slices.Concat(r.Options, opts)
path := "functions"
err = requestconfig.ExecuteNewRequest(ctx, http.MethodPost, path, body, &res, opts...)
return res, err
}
// Returns detailed information about an MCP server function including its
// deployment status, available tools, transport configuration, and endpoint URL.
func (r *FunctionService) Get(ctx context.Context, functionName string, query FunctionGetParams, opts ...option.RequestOption) (res *Function, err error) {
opts = slices.Concat(r.Options, opts)
if functionName == "" {
err = errors.New("missing required functionName parameter")
return nil, err
}
path := fmt.Sprintf("functions/%s", functionName)
err = requestconfig.ExecuteNewRequest(ctx, http.MethodGet, path, query, &res, opts...)
return res, err
}
// Updates an MCP server function's configuration and triggers a new deployment.
// Changes to runtime settings, integrations, or transport protocol will be applied
// on the next deployment.
func (r *FunctionService) Update(ctx context.Context, functionName string, body FunctionUpdateParams, opts ...option.RequestOption) (res *Function, err error) {
opts = slices.Concat(r.Options, opts)
if functionName == "" {
err = errors.New("missing required functionName parameter")
return nil, err
}
path := fmt.Sprintf("functions/%s", functionName)
err = requestconfig.ExecuteNewRequest(ctx, http.MethodPut, path, body, &res, opts...)
return res, err
}
// Returns MCP server functions deployed in the workspace. Each function includes
// its deployment status, transport protocol (websocket or http-stream), and
// endpoint URL. Starting with API version 2026-04-28 the response is wrapped in
// `{data, meta}` and supports cursor pagination via the `cursor` and `limit` query
// parameters; older versions keep returning a bare array with all functions.
func (r *FunctionService) List(ctx context.Context, query FunctionListParams, opts ...option.RequestOption) (res *pagination.CursorPage[Function], err error) {
var raw *http.Response
opts = slices.Concat(r.Options, opts)
opts = append([]option.RequestOption{option.WithResponseInto(&raw)}, opts...)
path := "functions"
cfg, err := requestconfig.NewRequestConfig(ctx, http.MethodGet, path, query, &res, opts...)
if err != nil {
return nil, err
}
err = cfg.Execute()
if err != nil {
return nil, err
}
res.SetPageConfig(cfg, raw)
return res, nil
}
// Returns MCP server functions deployed in the workspace. Each function includes
// its deployment status, transport protocol (websocket or http-stream), and
// endpoint URL. Starting with API version 2026-04-28 the response is wrapped in
// `{data, meta}` and supports cursor pagination via the `cursor` and `limit` query
// parameters; older versions keep returning a bare array with all functions.
func (r *FunctionService) ListAutoPaging(ctx context.Context, query FunctionListParams, opts ...option.RequestOption) *pagination.CursorPageAutoPager[Function] {
return pagination.NewCursorPageAutoPager(r.List(ctx, query, opts...))
}
// Permanently deletes an MCP server function and all its deployment history. Any
// agents using this function's tools will no longer be able to invoke them.
func (r *FunctionService) Delete(ctx context.Context, functionName string, opts ...option.RequestOption) (res *Function, err error) {
opts = slices.Concat(r.Options, opts)
if functionName == "" {
err = errors.New("missing required functionName parameter")
return nil, err
}
path := fmt.Sprintf("functions/%s", functionName)
err = requestconfig.ExecuteNewRequest(ctx, http.MethodDelete, path, nil, &res, opts...)
return res, err
}
// Returns revisions for a function by name.
func (r *FunctionService) ListRevisions(ctx context.Context, functionName string, opts ...option.RequestOption) (res *[]RevisionMetadata, err error) {
opts = slices.Concat(r.Options, opts)
if functionName == "" {
err = errors.New("missing required functionName parameter")
return nil, err
}
path := fmt.Sprintf("functions/%s/revisions", functionName)
err = requestconfig.ExecuteNewRequest(ctx, http.MethodGet, path, nil, &res, opts...)
return res, err
}
// MCP server deployment that exposes tools for AI agents via the Model Context
// Protocol (MCP). Deployed as a serverless auto-scaling endpoint using streamable
// HTTP transport.
type Function struct {
// Common metadata fields shared by all Blaxel resources including name, labels,
// timestamps, and ownership information
Metadata Metadata `json:"metadata" api:"required"`
// Configuration for an MCP server function including runtime settings, transport
// protocol, and connected integrations
Spec FunctionSpec `json:"spec" api:"required"`
// Events happening on a resource deployed on Blaxel
Events []CoreEvent `json:"events"`
// Deployment status of a resource deployed on Blaxel
//
// Any of "DELETING", "TERMINATED", "FAILED", "DEACTIVATED", "DEACTIVATING",
// "UPLOADING", "BUILDING", "DEPLOYING", "DEPLOYED", "BUILT", "ARCHIVING",
// "ARCHIVED", "UNARCHIVING".
Status Status `json:"status"`
// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
JSON struct {
Metadata respjson.Field
Spec respjson.Field
Events respjson.Field
Status respjson.Field
ExtraFields map[string]respjson.Field
raw string
} `json:"-"`
}
// Returns the unmodified JSON received from the API
func (r Function) RawJSON() string { return r.JSON.raw }
func (r *Function) UnmarshalJSON(data []byte) error {
return apijson.UnmarshalRoot(data, r)
}
// ToParam converts this Function to a FunctionParam.
//
// Warning: the fields of the param type will not be present. ToParam should only
// be used at the last possible moment before sending a request. Test for this with
// FunctionParam.Overrides()
func (r Function) ToParam() FunctionParam {
return param.Override[FunctionParam](json.RawMessage(r.RawJSON()))
}
// MCP server deployment that exposes tools for AI agents via the Model Context
// Protocol (MCP). Deployed as a serverless auto-scaling endpoint using streamable
// HTTP transport.
//
// The properties Metadata, Spec are required.
type FunctionParam struct {
// Common metadata fields shared by all Blaxel resources including name, labels,
// timestamps, and ownership information
Metadata MetadataParam `json:"metadata,omitzero" api:"required"`
// Configuration for an MCP server function including runtime settings, transport
// protocol, and connected integrations
Spec FunctionSpecParam `json:"spec,omitzero" api:"required"`
paramObj
}
func (r FunctionParam) MarshalJSON() (data []byte, err error) {
type shadow FunctionParam
return param.MarshalObject(r, (*shadow)(&r))
}
func (r *FunctionParam) UnmarshalJSON(data []byte) error {
return apijson.UnmarshalRoot(data, r)
}
// Runtime configuration defining how the MCP server function is deployed and
// scaled
type FunctionRuntime struct {
// Environment variables injected into the function. Supports Kubernetes EnvVar
// format with valueFrom references.
Envs []shared.Env `json:"envs"`
// Infrastructure generation: mk2 (containers, 2-10s cold starts, 15+ global
// regions) or mk3 (microVMs, sub-25ms cold starts)
//
// Any of "mk2", "mk3".
Generation FunctionRuntimeGeneration `json:"generation"`
// Container image built by Blaxel when deploying with 'bl deploy'. This field is
// auto-populated during deployment.
Image string `json:"image"`
// Maximum number of concurrent function instances for auto-scaling
MaxScale int64 `json:"maxScale"`
// Memory allocation in megabytes. Also determines CPU allocation (CPU cores =
// memory in MB / 2048, e.g., 4096MB = 2 CPUs).
Memory int64 `json:"memory"`
// Minimum instances to keep warm. Set to 1+ to eliminate cold starts, 0 for
// scale-to-zero.
MinScale int64 `json:"minScale"`
// Set of ports for a resource
Ports []Port `json:"ports"`
// Transport compatibility for the MCP, can be "websocket" or "http-stream"
//
// Any of "websocket", "http-stream".
Transport FunctionRuntimeTransport `json:"transport"`
// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
JSON struct {
Envs respjson.Field
Generation respjson.Field
Image respjson.Field
MaxScale respjson.Field
Memory respjson.Field
MinScale respjson.Field
Ports respjson.Field
Transport respjson.Field
ExtraFields map[string]respjson.Field
raw string
} `json:"-"`
}
// Returns the unmodified JSON received from the API
func (r FunctionRuntime) RawJSON() string { return r.JSON.raw }
func (r *FunctionRuntime) UnmarshalJSON(data []byte) error {
return apijson.UnmarshalRoot(data, r)
}
// ToParam converts this FunctionRuntime to a FunctionRuntimeParam.
//
// Warning: the fields of the param type will not be present. ToParam should only
// be used at the last possible moment before sending a request. Test for this with
// FunctionRuntimeParam.Overrides()
func (r FunctionRuntime) ToParam() FunctionRuntimeParam {
return param.Override[FunctionRuntimeParam](json.RawMessage(r.RawJSON()))
}
// Infrastructure generation: mk2 (containers, 2-10s cold starts, 15+ global
// regions) or mk3 (microVMs, sub-25ms cold starts)
type FunctionRuntimeGeneration string
const (
FunctionRuntimeGenerationMk2 FunctionRuntimeGeneration = "mk2"
FunctionRuntimeGenerationMk3 FunctionRuntimeGeneration = "mk3"
)
// Transport compatibility for the MCP, can be "websocket" or "http-stream"
type FunctionRuntimeTransport string
const (
FunctionRuntimeTransportWebsocket FunctionRuntimeTransport = "websocket"
FunctionRuntimeTransportHTTPStream FunctionRuntimeTransport = "http-stream"
)
// Runtime configuration defining how the MCP server function is deployed and
// scaled
type FunctionRuntimeParam struct {
// Container image built by Blaxel when deploying with 'bl deploy'. This field is
// auto-populated during deployment.
Image param.Opt[string] `json:"image,omitzero"`
// Maximum number of concurrent function instances for auto-scaling
MaxScale param.Opt[int64] `json:"maxScale,omitzero"`
// Memory allocation in megabytes. Also determines CPU allocation (CPU cores =
// memory in MB / 2048, e.g., 4096MB = 2 CPUs).
Memory param.Opt[int64] `json:"memory,omitzero"`
// Minimum instances to keep warm. Set to 1+ to eliminate cold starts, 0 for
// scale-to-zero.
MinScale param.Opt[int64] `json:"minScale,omitzero"`
// Environment variables injected into the function. Supports Kubernetes EnvVar
// format with valueFrom references.
Envs []shared.EnvParam `json:"envs,omitzero"`
// Infrastructure generation: mk2 (containers, 2-10s cold starts, 15+ global
// regions) or mk3 (microVMs, sub-25ms cold starts)
//
// Any of "mk2", "mk3".
Generation FunctionRuntimeGeneration `json:"generation,omitzero"`
// Set of ports for a resource
Ports []PortParam `json:"ports,omitzero"`
// Transport compatibility for the MCP, can be "websocket" or "http-stream"
//
// Any of "websocket", "http-stream".
Transport FunctionRuntimeTransport `json:"transport,omitzero"`
paramObj
}
func (r FunctionRuntimeParam) MarshalJSON() (data []byte, err error) {
type shadow FunctionRuntimeParam
return param.MarshalObject(r, (*shadow)(&r))
}
func (r *FunctionRuntimeParam) UnmarshalJSON(data []byte) error {
return apijson.UnmarshalRoot(data, r)
}
// Configuration for an MCP server function including runtime settings, transport
// protocol, and connected integrations
type FunctionSpec struct {
// When false, the function is disabled and will not serve requests
Enabled bool `json:"enabled"`
IntegrationConnections []string `json:"integrationConnections"`
Policies []string `json:"policies"`
// When true, the function is publicly accessible without authentication. Only
// available for mk3 generation.
Public bool `json:"public"`
// Region where the function should be deployed (e.g. us-pdx-1, eu-lon-1). If not
// specified, the function is deployed based on policy locations.
Region string `json:"region"`
// Revision configuration
Revision RevisionConfiguration `json:"revision"`
// Runtime configuration defining how the MCP server function is deployed and
// scaled
Runtime FunctionRuntime `json:"runtime"`
// Triggers to use your agent
Triggers []Trigger `json:"triggers"`
// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
JSON struct {
Enabled respjson.Field
IntegrationConnections respjson.Field
Policies respjson.Field
Public respjson.Field
Region respjson.Field
Revision respjson.Field
Runtime respjson.Field
Triggers respjson.Field
ExtraFields map[string]respjson.Field
raw string
} `json:"-"`
}
// Returns the unmodified JSON received from the API
func (r FunctionSpec) RawJSON() string { return r.JSON.raw }
func (r *FunctionSpec) UnmarshalJSON(data []byte) error {
return apijson.UnmarshalRoot(data, r)
}
// ToParam converts this FunctionSpec to a FunctionSpecParam.
//
// Warning: the fields of the param type will not be present. ToParam should only
// be used at the last possible moment before sending a request. Test for this with
// FunctionSpecParam.Overrides()
func (r FunctionSpec) ToParam() FunctionSpecParam {
return param.Override[FunctionSpecParam](json.RawMessage(r.RawJSON()))
}
// Configuration for an MCP server function including runtime settings, transport
// protocol, and connected integrations
type FunctionSpecParam struct {
// When false, the function is disabled and will not serve requests
Enabled param.Opt[bool] `json:"enabled,omitzero"`
// When true, the function is publicly accessible without authentication. Only
// available for mk3 generation.
Public param.Opt[bool] `json:"public,omitzero"`
// Region where the function should be deployed (e.g. us-pdx-1, eu-lon-1). If not
// specified, the function is deployed based on policy locations.
Region param.Opt[string] `json:"region,omitzero"`
IntegrationConnections []string `json:"integrationConnections,omitzero"`
Policies []string `json:"policies,omitzero"`
// Revision configuration
Revision RevisionConfigurationParam `json:"revision,omitzero"`
// Runtime configuration defining how the MCP server function is deployed and
// scaled
Runtime FunctionRuntimeParam `json:"runtime,omitzero"`
// Triggers to use your agent
Triggers []TriggerParam `json:"triggers,omitzero"`
paramObj
}
func (r FunctionSpecParam) MarshalJSON() (data []byte, err error) {
type shadow FunctionSpecParam
return param.MarshalObject(r, (*shadow)(&r))
}
func (r *FunctionSpecParam) UnmarshalJSON(data []byte) error {
return apijson.UnmarshalRoot(data, r)
}
type FunctionNewParams struct {
// MCP server deployment that exposes tools for AI agents via the Model Context
// Protocol (MCP). Deployed as a serverless auto-scaling endpoint using streamable
// HTTP transport.
Function FunctionParam
paramObj
}
func (r FunctionNewParams) MarshalJSON() (data []byte, err error) {
return shimjson.Marshal(r.Function)
}
func (r *FunctionNewParams) UnmarshalJSON(data []byte) error {
return apijson.UnmarshalRoot(data, r)
}
type FunctionGetParams struct {
// Show secret values (requires workspace admin role)
ShowSecrets param.Opt[bool] `query:"show_secrets,omitzero" json:"-"`
paramObj
}
// URLQuery serializes [FunctionGetParams]'s query parameters as `url.Values`.
func (r FunctionGetParams) URLQuery() (v url.Values, err error) {
return apiquery.MarshalWithSettings(r, apiquery.QuerySettings{
ArrayFormat: apiquery.ArrayQueryFormatComma,
NestedFormat: apiquery.NestedQueryFormatBrackets,
})
}
type FunctionUpdateParams struct {
// MCP server deployment that exposes tools for AI agents via the Model Context
// Protocol (MCP). Deployed as a serverless auto-scaling endpoint using streamable
// HTTP transport.
Function FunctionParam
paramObj
}
func (r FunctionUpdateParams) MarshalJSON() (data []byte, err error) {
return shimjson.Marshal(r.Function)
}
func (r *FunctionUpdateParams) UnmarshalJSON(data []byte) error {
return apijson.UnmarshalRoot(data, r)
}
type FunctionListParams struct {
// Opaque cursor returned by a previous response's meta.nextCursor. Only valid for
// the same query (workspace + filters); the server rejects cursors bound to a
// different query or older than 24h. Omit on the first page.
Cursor param.Opt[string] `query:"cursor,omitzero" json:"-"`
// Filter resources by metadata.externalId. When set, only resources matching this
// caller-owned external ID are returned.
ExternalID param.Opt[string] `query:"externalId,omitzero" json:"-"`
// Maximum number of items to return per page. Defaults to 50, clamped to 200.
Limit param.Opt[int64] `query:"limit,omitzero" json:"-"`
// Substring search across `metadata.name`, `metadata.displayName` and labels
// (keys + values). Trimmed and lowercased server-side; queries shorter than 2
// characters fall back to the unfiltered listing. Bound into the cursor
// fingerprint so a cursor opened with one query cannot be reused with another.
// Only honoured starting on Blaxel-Version 2026-04-28.
Q param.Opt[string] `query:"q,omitzero" json:"-"`
// Comma-separated list of statuses to filter on (e.g. `DEPLOYED,FAILED`). Values
// are case-insensitive; unknown values are rejected with a 400. Selecting every
// status is equivalent to omitting the parameter. Bound into the cursor
// fingerprint so a cursor opened with one selection cannot be reused with another.
// Filtering itself requires the 2026-04-28 Blaxel-Version (the paginated listing);
// on earlier versions the value is still validated but the listing is unfiltered,
// except for sandboxes where it is applied on every version.
Status param.Opt[string] `query:"status,omitzero" json:"-"`
// Start from a known pagination boundary. `end` is only supported for `createdAt`
// listings (asc or desc) and returns the tail page directly without walking every
// cursor from the first page.
//
// Any of "end".
Anchor FunctionListParamsAnchor `query:"anchor,omitzero" json:"-"`
// Sort spec, formatted as `<key>:<direction>`. Allowed values are `createdAt:desc`
// (default), `createdAt:asc`, `name:asc`, `name:desc`. The cursor fingerprint is
// bound to the sort, so a cursor opened with one value cannot be reused with
// another. Only honoured starting on Blaxel-Version 2026-04-28.
//
// Any of "createdAt:desc", "createdAt:asc", "name:asc", "name:desc".
Sort FunctionListParamsSort `query:"sort,omitzero" json:"-"`
paramObj
}
// URLQuery serializes [FunctionListParams]'s query parameters as `url.Values`.
func (r FunctionListParams) URLQuery() (v url.Values, err error) {
return apiquery.MarshalWithSettings(r, apiquery.QuerySettings{
ArrayFormat: apiquery.ArrayQueryFormatComma,
NestedFormat: apiquery.NestedQueryFormatBrackets,
})
}
// Start from a known pagination boundary. `end` is only supported for `createdAt`
// listings (asc or desc) and returns the tail page directly without walking every
// cursor from the first page.
type FunctionListParamsAnchor string
const (
FunctionListParamsAnchorEnd FunctionListParamsAnchor = "end"
)
// Sort spec, formatted as `<key>:<direction>`. Allowed values are `createdAt:desc`
// (default), `createdAt:asc`, `name:asc`, `name:desc`. The cursor fingerprint is
// bound to the sort, so a cursor opened with one value cannot be reused with
// another. Only honoured starting on Blaxel-Version 2026-04-28.
type FunctionListParamsSort string
const (
FunctionListParamsSortCreatedAtDesc FunctionListParamsSort = "createdAt:desc"
FunctionListParamsSortCreatedAtAsc FunctionListParamsSort = "createdAt:asc"
FunctionListParamsSortNameAsc FunctionListParamsSort = "name:asc"
FunctionListParamsSortNameDesc FunctionListParamsSort = "name:desc"
)