server.go 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920
  1. package mcp
  2. import (
  3. "context"
  4. "crypto/rand"
  5. "encoding/hex"
  6. "fmt"
  7. "strings"
  8. "time"
  9. "github.com/go-playground/validator/v10"
  10. "github.com/opencost/opencost/core/pkg/filter"
  11. "github.com/opencost/opencost/core/pkg/filter/allocation"
  12. cloudcostfilter "github.com/opencost/opencost/core/pkg/filter/cloudcost"
  13. "github.com/opencost/opencost/core/pkg/opencost"
  14. models "github.com/opencost/opencost/pkg/cloud/models"
  15. "github.com/opencost/opencost/pkg/cloudcost"
  16. "github.com/opencost/opencost/pkg/costmodel"
  17. )
  18. // QueryType defines the type of query to be executed.
  19. type QueryType string
  20. const (
  21. AllocationQueryType QueryType = "allocation"
  22. AssetQueryType QueryType = "asset"
  23. CloudCostQueryType QueryType = "cloudcost"
  24. )
  25. // MCPRequest represents a single turn in a conversation with the OpenCost MCP server.
  26. type MCPRequest struct {
  27. SessionID string `json:"sessionId"`
  28. Query *OpenCostQueryRequest `json:"query"`
  29. }
  30. // MCPResponse is the response from the OpenCost MCP server for a single turn.
  31. type MCPResponse struct {
  32. Data interface{} `json:"data"`
  33. QueryInfo QueryMetadata `json:"queryInfo"`
  34. }
  35. // QueryMetadata contains metadata about the query execution.
  36. type QueryMetadata struct {
  37. QueryID string `json:"queryId"`
  38. Timestamp time.Time `json:"timestamp"`
  39. ProcessingTime time.Duration `json:"processingTime"`
  40. }
  41. // OpenCostQueryRequest provides a unified interface for all OpenCost query types.
  42. type OpenCostQueryRequest struct {
  43. QueryType QueryType `json:"queryType" validate:"required,oneof=allocation asset cloudcost"`
  44. Window string `json:"window" validate:"required"`
  45. AllocationParams *AllocationQuery `json:"allocationParams,omitempty"`
  46. AssetParams *AssetQuery `json:"assetParams,omitempty"`
  47. CloudCostParams *CloudCostQuery `json:"cloudCostParams,omitempty"`
  48. }
  49. // AllocationQuery contains the parameters for an allocation query.
  50. type AllocationQuery struct {
  51. Step time.Duration `json:"step,omitempty"`
  52. Accumulate bool `json:"accumulate,omitempty"`
  53. ShareIdle bool `json:"shareIdle,omitempty"`
  54. Aggregate string `json:"aggregate,omitempty"`
  55. IncludeIdle bool `json:"includeIdle,omitempty"`
  56. IdleByNode bool `json:"idleByNode,omitempty"`
  57. IncludeProportionalAssetResourceCosts bool `json:"includeProportionalAssetResourceCosts,omitempty"`
  58. IncludeAggregatedMetadata bool `json:"includeAggregatedMetadata,omitempty"`
  59. ShareLB bool `json:"sharelb,omitempty"`
  60. Filter string `json:"filter,omitempty"` // Filter expression for allocations (e.g., "cluster:production", "namespace:kube-system")
  61. }
  62. // AssetQuery contains the parameters for an asset query.
  63. type AssetQuery struct {
  64. // Currently no specific parameters needed for asset queries as it only takes window as parameter
  65. }
  66. // CloudCostQuery contains the parameters for a cloud cost query.
  67. type CloudCostQuery struct {
  68. Aggregate string `json:"aggregate,omitempty"` // Comma-separated list of aggregation properties
  69. Accumulate string `json:"accumulate,omitempty"` // e.g., "week", "day", "month"
  70. Filter string `json:"filter,omitempty"` // Filter expression for cloud costs
  71. Provider string `json:"provider,omitempty"` // Cloud provider filter (aws, gcp, azure, etc.)
  72. Service string `json:"service,omitempty"` // Service filter (ec2, s3, compute, etc.)
  73. Category string `json:"category,omitempty"` // Category filter (compute, storage, network, etc.)
  74. Region string `json:"region,omitempty"` // Region filter
  75. // Additional explicit fields for filtering
  76. AccountID string `json:"accountID,omitempty"` // Alias of Account; maps to accountID
  77. InvoiceEntityID string `json:"invoiceEntityID,omitempty"` // Invoice entity ID filter
  78. ProviderID string `json:"providerID,omitempty"` // Cloud provider resource ID filter
  79. Labels map[string]string `json:"labels,omitempty"` // Label filters (key->value)
  80. }
  81. // AllocationResponse represents the allocation data returned to the AI agent.
  82. type AllocationResponse struct {
  83. // The allocation data, as a map of allocation sets.
  84. Allocations map[string]*AllocationSet `json:"allocations"`
  85. }
  86. // AllocationSet represents a set of allocation data.
  87. type AllocationSet struct {
  88. // The name of the allocation set.
  89. Name string `json:"name"`
  90. Properties map[string]string `json:"properties"`
  91. Allocations []*Allocation `json:"allocations"`
  92. }
  93. // TotalCost calculates the total cost of all allocations in the set.
  94. func (as *AllocationSet) TotalCost() float64 {
  95. var total float64
  96. for _, alloc := range as.Allocations {
  97. total += alloc.TotalCost
  98. }
  99. return total
  100. }
  101. // Allocation represents a single allocation data point.
  102. type Allocation struct {
  103. Name string `json:"name"` // Allocation key (namespace, cluster, etc.)
  104. CPUCost float64 `json:"cpuCost"` // Cost of CPU usage
  105. GPUCost float64 `json:"gpuCost"` // Cost of GPU usage
  106. RAMCost float64 `json:"ramCost"` // Cost of memory usage
  107. PVCost float64 `json:"pvCost"` // Cost of persistent volumes
  108. NetworkCost float64 `json:"networkCost"` // Cost of network usage
  109. SharedCost float64 `json:"sharedCost"` // Shared/unallocated costs assigned here
  110. ExternalCost float64 `json:"externalCost"` // External costs (cloud services, etc.)
  111. TotalCost float64 `json:"totalCost"` // Sum of all costs above
  112. CPUCoreHours float64 `json:"cpuCoreHours"` // Usage metrics: CPU core-hours
  113. RAMByteHours float64 `json:"ramByteHours"` // Usage metrics: RAM byte-hours
  114. GPUHours float64 `json:"gpuHours"` // Usage metrics: GPU-hours
  115. PVByteHours float64 `json:"pvByteHours"` // Usage metrics: PV byte-hours
  116. Start time.Time `json:"start"` // Start timestamp for this allocation
  117. End time.Time `json:"end"` // End timestamp for this allocation
  118. }
  119. // AssetResponse represents the asset data returned to the AI agent.
  120. type AssetResponse struct {
  121. // The asset data, as a map of asset sets.
  122. Assets map[string]*AssetSet `json:"assets"`
  123. }
  124. // AssetSet represents a set of asset data.
  125. type AssetSet struct {
  126. // The name of the asset set.
  127. Name string `json:"name"`
  128. // The asset data for the set.
  129. Assets []*Asset `json:"assets"`
  130. }
  131. // Asset represents a single asset data point.
  132. type Asset struct {
  133. Type string `json:"type"`
  134. Properties AssetProperties `json:"properties"`
  135. Labels map[string]string `json:"labels,omitempty"`
  136. Start time.Time `json:"start"`
  137. End time.Time `json:"end"`
  138. Minutes float64 `json:"minutes"`
  139. Adjustment float64 `json:"adjustment"`
  140. TotalCost float64 `json:"totalCost"`
  141. // Disk-specific fields
  142. ByteHours float64 `json:"byteHours,omitempty"`
  143. ByteHoursUsed *float64 `json:"byteHoursUsed,omitempty"`
  144. ByteUsageMax *float64 `json:"byteUsageMax,omitempty"`
  145. StorageClass string `json:"storageClass,omitempty"`
  146. VolumeName string `json:"volumeName,omitempty"`
  147. ClaimName string `json:"claimName,omitempty"`
  148. ClaimNamespace string `json:"claimNamespace,omitempty"`
  149. Local float64 `json:"local,omitempty"`
  150. // Node-specific fields
  151. NodeType string `json:"nodeType,omitempty"`
  152. CPUCoreHours float64 `json:"cpuCoreHours,omitempty"`
  153. RAMByteHours float64 `json:"ramByteHours,omitempty"`
  154. GPUHours float64 `json:"gpuHours,omitempty"`
  155. GPUCount float64 `json:"gpuCount,omitempty"`
  156. CPUCost float64 `json:"cpuCost,omitempty"`
  157. GPUCost float64 `json:"gpuCost,omitempty"`
  158. RAMCost float64 `json:"ramCost,omitempty"`
  159. Discount float64 `json:"discount,omitempty"`
  160. Preemptible float64 `json:"preemptible,omitempty"`
  161. // Breakdown fields (can be used for different types)
  162. Breakdown *AssetBreakdown `json:"breakdown,omitempty"`
  163. CPUBreakdown *AssetBreakdown `json:"cpuBreakdown,omitempty"`
  164. RAMBreakdown *AssetBreakdown `json:"ramBreakdown,omitempty"`
  165. // Overhead (Node-specific)
  166. Overhead *NodeOverhead `json:"overhead,omitempty"`
  167. // LoadBalancer-specific fields
  168. Private bool `json:"private,omitempty"`
  169. Ip string `json:"ip,omitempty"`
  170. // Cloud-specific fields
  171. Credit float64 `json:"credit,omitempty"`
  172. }
  173. // NodeOverhead represents node overhead information
  174. type NodeOverhead struct {
  175. RamOverheadFraction float64 `json:"ramOverheadFraction"`
  176. CpuOverheadFraction float64 `json:"cpuOverheadFraction"`
  177. OverheadCostFraction float64 `json:"overheadCostFraction"`
  178. }
  179. type AssetProperties struct {
  180. Category string `json:"category,omitempty"`
  181. Provider string `json:"provider,omitempty"`
  182. Account string `json:"account,omitempty"`
  183. Project string `json:"project,omitempty"`
  184. Service string `json:"service,omitempty"`
  185. Cluster string `json:"cluster,omitempty"`
  186. Name string `json:"name,omitempty"`
  187. ProviderID string `json:"providerID,omitempty"`
  188. }
  189. type AssetBreakdown struct {
  190. Idle float64 `json:"idle"`
  191. Other float64 `json:"other"`
  192. System float64 `json:"system"`
  193. User float64 `json:"user"`
  194. }
  195. // CloudCostResponse represents the cloud cost data returned to the AI agent.
  196. type CloudCostResponse struct {
  197. // The cloud cost data, as a map of cloud cost sets.
  198. CloudCosts map[string]*CloudCostSet `json:"cloudCosts"`
  199. // Summary information
  200. Summary *CloudCostSummary `json:"summary,omitempty"`
  201. }
  202. // CloudCostSummary provides summary information about cloud costs
  203. type CloudCostSummary struct {
  204. TotalNetCost float64 `json:"totalNetCost"`
  205. TotalAmortizedCost float64 `json:"totalAmortizedCost"`
  206. TotalInvoicedCost float64 `json:"totalInvoicedCost"`
  207. KubernetesPercent float64 `json:"kubernetesPercent"`
  208. ProviderBreakdown map[string]float64 `json:"providerBreakdown,omitempty"`
  209. ServiceBreakdown map[string]float64 `json:"serviceBreakdown,omitempty"`
  210. RegionBreakdown map[string]float64 `json:"regionBreakdown,omitempty"`
  211. }
  212. // CloudCostSet represents a set of cloud cost data.
  213. type CloudCostSet struct {
  214. // The name of the cloud cost set.
  215. Name string `json:"name"`
  216. // The cloud cost data for the set.
  217. CloudCosts []*CloudCost `json:"cloudCosts"`
  218. // Aggregation information
  219. AggregationProperties []string `json:"aggregationProperties,omitempty"`
  220. // Time window
  221. Window *TimeWindow `json:"window,omitempty"`
  222. }
  223. // TimeWindow represents a time range
  224. type TimeWindow struct {
  225. Start time.Time `json:"start"`
  226. End time.Time `json:"end"`
  227. }
  228. // CloudCostProperties defines the properties of a cloud cost item.
  229. type CloudCostProperties struct {
  230. ProviderID string `json:"providerID,omitempty"`
  231. Provider string `json:"provider,omitempty"`
  232. AccountID string `json:"accountID,omitempty"`
  233. AccountName string `json:"accountName,omitempty"`
  234. InvoiceEntityID string `json:"invoiceEntityID,omitempty"`
  235. InvoiceEntityName string `json:"invoiceEntityName,omitempty"`
  236. RegionID string `json:"regionID,omitempty"`
  237. AvailabilityZone string `json:"availabilityZone,omitempty"`
  238. Service string `json:"service,omitempty"`
  239. Category string `json:"category,omitempty"`
  240. Labels map[string]string `json:"labels,omitempty"`
  241. }
  242. // CloudCost represents a single cloud cost data point.
  243. type CloudCost struct {
  244. Properties CloudCostProperties `json:"properties"`
  245. Window TimeWindow `json:"window"`
  246. ListCost CostMetric `json:"listCost"`
  247. NetCost CostMetric `json:"netCost"`
  248. AmortizedNetCost CostMetric `json:"amortizedNetCost"`
  249. InvoicedCost CostMetric `json:"invoicedCost"`
  250. AmortizedCost CostMetric `json:"amortizedCost"`
  251. }
  252. // CostMetric represents a cost value with Kubernetes percentage
  253. type CostMetric struct {
  254. Cost float64 `json:"cost"`
  255. KubernetesPercent float64 `json:"kubernetesPercent"`
  256. }
  257. // MCPServer holds the dependencies for the MCP API server.
  258. type MCPServer struct {
  259. costModel *costmodel.CostModel
  260. provider models.Provider
  261. cloudQuerier cloudcost.Querier
  262. }
  263. // NewMCPServer creates a new MCP Server.
  264. func NewMCPServer(costModel *costmodel.CostModel, provider models.Provider, cloudQuerier cloudcost.Querier) *MCPServer {
  265. return &MCPServer{
  266. costModel: costModel,
  267. provider: provider,
  268. cloudQuerier: cloudQuerier,
  269. }
  270. }
  271. // ProcessMCPRequest processes an MCP request and returns an MCP response.
  272. func (s *MCPServer) ProcessMCPRequest(request *MCPRequest) (*MCPResponse, error) {
  273. // 1. Validate Request
  274. if err := validate.Struct(request); err != nil {
  275. return nil, fmt.Errorf("validation failed: %w", err)
  276. }
  277. // 2. Query Dispatching
  278. var data interface{}
  279. var err error
  280. queryStart := time.Now()
  281. switch request.Query.QueryType {
  282. case AllocationQueryType:
  283. data, err = s.QueryAllocations(request.Query)
  284. case AssetQueryType:
  285. data, err = s.QueryAssets(request.Query)
  286. case CloudCostQueryType:
  287. data, err = s.QueryCloudCosts(request.Query)
  288. default:
  289. return nil, fmt.Errorf("unsupported query type: %s", request.Query.QueryType)
  290. }
  291. if err != nil {
  292. // Handle error appropriately, maybe return a JSON-RPC error response
  293. return nil, err
  294. }
  295. processingTime := time.Since(queryStart)
  296. // 3. Construct Final Response
  297. mcpResponse := &MCPResponse{
  298. Data: data,
  299. QueryInfo: QueryMetadata{
  300. QueryID: generateQueryID(),
  301. Timestamp: time.Now(),
  302. ProcessingTime: processingTime,
  303. },
  304. }
  305. return mcpResponse, nil
  306. }
  307. // validate is the singleton validator instance.
  308. var validate = validator.New()
  309. func generateQueryID() string {
  310. bytes := make([]byte, 8) // 16 hex characters
  311. if _, err := rand.Read(bytes); err != nil {
  312. // Fallback to timestamp-based ID if crypto/rand fails
  313. return fmt.Sprintf("query-%d", time.Now().UnixNano())
  314. }
  315. return fmt.Sprintf("query-%s", hex.EncodeToString(bytes))
  316. }
  317. func (s *MCPServer) QueryAllocations(query *OpenCostQueryRequest) (*AllocationResponse, error) {
  318. // 1. Parse Window
  319. window, err := opencost.ParseWindowWithOffset(query.Window, 0) // 0 offset for UTC
  320. if err != nil {
  321. return nil, fmt.Errorf("failed to parse window '%s': %w", query.Window, err)
  322. }
  323. // 2. Set default parameters
  324. var step time.Duration
  325. var aggregateBy []string
  326. var includeIdle, idleByNode, includeProportionalAssetResourceCosts, includeAggregatedMetadata, sharedLoadBalancer, shareIdle bool
  327. var accumulateBy opencost.AccumulateOption
  328. var filterString string
  329. // 3. Parse allocation parameters if provided
  330. if query.AllocationParams != nil {
  331. // Set step duration (default to window duration if not specified)
  332. if query.AllocationParams.Step > 0 {
  333. step = query.AllocationParams.Step
  334. } else {
  335. step = window.Duration()
  336. }
  337. // Parse aggregation properties
  338. if query.AllocationParams.Aggregate != "" {
  339. aggregateBy = strings.Split(query.AllocationParams.Aggregate, ",")
  340. }
  341. // Set boolean parameters
  342. includeIdle = query.AllocationParams.IncludeIdle
  343. idleByNode = query.AllocationParams.IdleByNode
  344. includeProportionalAssetResourceCosts = query.AllocationParams.IncludeProportionalAssetResourceCosts
  345. includeAggregatedMetadata = query.AllocationParams.IncludeAggregatedMetadata
  346. sharedLoadBalancer = query.AllocationParams.ShareLB
  347. shareIdle = query.AllocationParams.ShareIdle
  348. // Set filter string
  349. filterString = query.AllocationParams.Filter
  350. // Validate filter string if provided
  351. if filterString != "" {
  352. parser := allocation.NewAllocationFilterParser()
  353. _, err := parser.Parse(filterString)
  354. if err != nil {
  355. return nil, fmt.Errorf("invalid allocation filter '%s': %w", filterString, err)
  356. }
  357. }
  358. // Set accumulation option
  359. if query.AllocationParams.Accumulate {
  360. accumulateBy = opencost.AccumulateOptionAll
  361. } else {
  362. accumulateBy = opencost.AccumulateOptionNone
  363. }
  364. } else {
  365. // Default values when no parameters provided
  366. step = window.Duration()
  367. accumulateBy = opencost.AccumulateOptionNone
  368. filterString = ""
  369. }
  370. // 4. Call the existing QueryAllocation function with all parameters
  371. asr, err := s.costModel.QueryAllocation(
  372. window,
  373. step,
  374. aggregateBy,
  375. includeIdle,
  376. idleByNode,
  377. includeProportionalAssetResourceCosts,
  378. includeAggregatedMetadata,
  379. sharedLoadBalancer,
  380. accumulateBy,
  381. shareIdle,
  382. filterString,
  383. )
  384. if err != nil {
  385. return nil, fmt.Errorf("failed to query allocations: %w", err)
  386. }
  387. // 5. Handle the AllocationSetRange result
  388. if asr == nil || len(asr.Allocations) == 0 {
  389. return &AllocationResponse{
  390. Allocations: make(map[string]*AllocationSet),
  391. }, nil
  392. }
  393. // 6. Transform the result to MCP format
  394. // If we have multiple sets, we'll combine them or return the first one
  395. // For now, let's return the first allocation set
  396. firstSet := asr.Allocations[0]
  397. return transformAllocationSet(firstSet), nil
  398. }
  399. // transformAllocationSet converts an opencost.AllocationSet into the MCP's AllocationResponse format.
  400. func transformAllocationSet(allocSet *opencost.AllocationSet) *AllocationResponse {
  401. if allocSet == nil {
  402. return &AllocationResponse{Allocations: make(map[string]*AllocationSet)}
  403. }
  404. mcpAllocations := make(map[string]*AllocationSet)
  405. // Create a single set for all allocations
  406. mcpSet := &AllocationSet{
  407. Name: "allocations",
  408. Allocations: []*Allocation{},
  409. }
  410. // Convert each allocation
  411. for _, alloc := range allocSet.Allocations {
  412. if alloc == nil {
  413. continue
  414. }
  415. mcpAlloc := &Allocation{
  416. Name: alloc.Name,
  417. CPUCost: alloc.CPUCost,
  418. GPUCost: alloc.GPUCost,
  419. RAMCost: alloc.RAMCost,
  420. PVCost: alloc.PVCost(), // Call the method
  421. NetworkCost: alloc.NetworkCost,
  422. SharedCost: alloc.SharedCost,
  423. ExternalCost: alloc.ExternalCost,
  424. TotalCost: alloc.TotalCost(),
  425. CPUCoreHours: alloc.CPUCoreHours,
  426. RAMByteHours: alloc.RAMByteHours,
  427. GPUHours: alloc.GPUHours,
  428. PVByteHours: alloc.PVBytes(), // Use the method directly
  429. Start: alloc.Start,
  430. End: alloc.End,
  431. }
  432. mcpSet.Allocations = append(mcpSet.Allocations, mcpAlloc)
  433. }
  434. mcpAllocations["allocations"] = mcpSet
  435. return &AllocationResponse{
  436. Allocations: mcpAllocations,
  437. }
  438. }
  439. func (s *MCPServer) QueryAssets(query *OpenCostQueryRequest) (*AssetResponse, error) {
  440. // 1. Parse Window
  441. window, err := opencost.ParseWindowWithOffset(query.Window, 0) // 0 offset for UTC
  442. if err != nil {
  443. return nil, fmt.Errorf("failed to parse window '%s': %w", query.Window, err)
  444. }
  445. // 2. Set Query Options
  446. start := *window.Start()
  447. end := *window.End()
  448. // 3. Call CostModel to get the asset set
  449. assetSet, err := s.costModel.ComputeAssets(start, end)
  450. if err != nil {
  451. return nil, fmt.Errorf("failed to compute assets: %w", err)
  452. }
  453. // 4. Transform Response for the MCP API
  454. return transformAssetSet(assetSet), nil
  455. }
  456. // transformAssetSet converts a opencost.AssetSet into the MCP's AssetResponse format.
  457. func transformAssetSet(assetSet *opencost.AssetSet) *AssetResponse {
  458. if assetSet == nil {
  459. return &AssetResponse{Assets: make(map[string]*AssetSet)}
  460. }
  461. mcpAssets := make(map[string]*AssetSet)
  462. // Create a single set for all assets
  463. mcpSet := &AssetSet{
  464. Name: "assets",
  465. Assets: []*Asset{},
  466. }
  467. for _, asset := range assetSet.Assets {
  468. if asset == nil {
  469. continue
  470. }
  471. properties := asset.GetProperties()
  472. labels := asset.GetLabels()
  473. mcpAsset := &Asset{
  474. Type: asset.Type().String(),
  475. Properties: AssetProperties{
  476. Category: properties.Category,
  477. Provider: properties.Provider,
  478. Account: properties.Account,
  479. Project: properties.Project,
  480. Service: properties.Service,
  481. Cluster: properties.Cluster,
  482. Name: properties.Name,
  483. ProviderID: properties.ProviderID,
  484. },
  485. Labels: labels,
  486. Start: asset.GetStart(),
  487. End: asset.GetEnd(),
  488. Minutes: asset.Minutes(),
  489. Adjustment: asset.GetAdjustment(),
  490. TotalCost: asset.TotalCost(),
  491. }
  492. // Handle type-specific fields
  493. switch a := asset.(type) {
  494. case *opencost.Disk:
  495. mcpAsset.ByteHours = a.ByteHours
  496. mcpAsset.ByteHoursUsed = a.ByteHoursUsed
  497. mcpAsset.ByteUsageMax = a.ByteUsageMax
  498. mcpAsset.StorageClass = a.StorageClass
  499. mcpAsset.VolumeName = a.VolumeName
  500. mcpAsset.ClaimName = a.ClaimName
  501. mcpAsset.ClaimNamespace = a.ClaimNamespace
  502. mcpAsset.Local = a.Local
  503. if a.Breakdown != nil {
  504. mcpAsset.Breakdown = &AssetBreakdown{
  505. Idle: a.Breakdown.Idle,
  506. Other: a.Breakdown.Other,
  507. System: a.Breakdown.System,
  508. User: a.Breakdown.User,
  509. }
  510. }
  511. case *opencost.Node:
  512. mcpAsset.NodeType = a.NodeType
  513. mcpAsset.CPUCoreHours = a.CPUCoreHours
  514. mcpAsset.RAMByteHours = a.RAMByteHours
  515. mcpAsset.GPUHours = a.GPUHours
  516. mcpAsset.GPUCount = a.GPUCount
  517. mcpAsset.CPUCost = a.CPUCost
  518. mcpAsset.GPUCost = a.GPUCost
  519. mcpAsset.RAMCost = a.RAMCost
  520. mcpAsset.Discount = a.Discount
  521. mcpAsset.Preemptible = a.Preemptible
  522. if a.CPUBreakdown != nil {
  523. mcpAsset.CPUBreakdown = &AssetBreakdown{
  524. Idle: a.CPUBreakdown.Idle,
  525. Other: a.CPUBreakdown.Other,
  526. System: a.CPUBreakdown.System,
  527. User: a.CPUBreakdown.User,
  528. }
  529. }
  530. if a.RAMBreakdown != nil {
  531. mcpAsset.RAMBreakdown = &AssetBreakdown{
  532. Idle: a.RAMBreakdown.Idle,
  533. Other: a.RAMBreakdown.Other,
  534. System: a.RAMBreakdown.System,
  535. User: a.RAMBreakdown.User,
  536. }
  537. }
  538. if a.Overhead != nil {
  539. mcpAsset.Overhead = &NodeOverhead{
  540. RamOverheadFraction: a.Overhead.RamOverheadFraction,
  541. CpuOverheadFraction: a.Overhead.CpuOverheadFraction,
  542. OverheadCostFraction: a.Overhead.OverheadCostFraction,
  543. }
  544. }
  545. case *opencost.LoadBalancer:
  546. mcpAsset.Private = a.Private
  547. mcpAsset.Ip = a.Ip
  548. case *opencost.Network:
  549. // Network assets have no specific fields beyond the base asset structure
  550. // All relevant data is in Properties, Labels, Cost, etc.
  551. case *opencost.Cloud:
  552. mcpAsset.Credit = a.Credit
  553. case *opencost.ClusterManagement:
  554. // ClusterManagement assets have no specific fields beyond the base asset structure
  555. // All relevant data is in Properties, Labels, Cost, etc.
  556. }
  557. mcpSet.Assets = append(mcpSet.Assets, mcpAsset)
  558. }
  559. mcpAssets["assets"] = mcpSet
  560. return &AssetResponse{
  561. Assets: mcpAssets,
  562. }
  563. }
  564. // QueryCloudCosts translates an MCP query into a CloudCost repository query and transforms the result.
  565. func (s *MCPServer) QueryCloudCosts(query *OpenCostQueryRequest) (*CloudCostResponse, error) {
  566. // 1. Check if cloud cost querier is available
  567. if s.cloudQuerier == nil {
  568. return nil, fmt.Errorf("cloud cost querier not configured - check cloud-integration.json file")
  569. }
  570. // 2. Parse Window
  571. window, err := opencost.ParseWindowWithOffset(query.Window, 0) // 0 offset for UTC
  572. if err != nil {
  573. return nil, fmt.Errorf("failed to parse window '%s': %w", query.Window, err)
  574. }
  575. // 3. Build query request
  576. request := cloudcost.QueryRequest{
  577. Start: *window.Start(),
  578. End: *window.End(),
  579. Filter: nil, // Will be set from CloudCostParams if provided
  580. }
  581. // 4. Apply filtering and aggregation from CloudCostParams
  582. if query.CloudCostParams != nil {
  583. request = s.buildCloudCostQueryRequest(request, query.CloudCostParams)
  584. }
  585. // 5. Query the repository (this handles multiple cloud providers automatically)
  586. ccsr, err := s.cloudQuerier.Query(context.TODO(), request)
  587. if err != nil {
  588. return nil, fmt.Errorf("failed to query cloud costs: %w", err)
  589. }
  590. // 6. Transform Response
  591. return transformCloudCostSetRange(ccsr), nil
  592. }
  593. // buildCloudCostQueryRequest builds a QueryRequest from CloudCostParams
  594. func (s *MCPServer) buildCloudCostQueryRequest(request cloudcost.QueryRequest, params *CloudCostQuery) cloudcost.QueryRequest {
  595. // Set aggregation
  596. if params.Aggregate != "" {
  597. aggregateBy := strings.Split(params.Aggregate, ",")
  598. request.AggregateBy = aggregateBy
  599. }
  600. // Set accumulation
  601. if params.Accumulate != "" {
  602. request.Accumulate = opencost.ParseAccumulate(params.Accumulate)
  603. }
  604. // Build filter from individual parameters or filter string
  605. var filter filter.Filter
  606. var err error
  607. if params.Filter != "" {
  608. // Parse the filter string directly
  609. parser := cloudcostfilter.NewCloudCostFilterParser()
  610. filter, err = parser.Parse(params.Filter)
  611. if err != nil {
  612. // Log error but continue without filter rather than failing the entire request
  613. fmt.Printf("Warning: failed to parse filter string '%s': %v\n", params.Filter, err)
  614. }
  615. } else {
  616. // Build filter from individual parameters
  617. filter = s.buildFilterFromParams(params)
  618. }
  619. request.Filter = filter
  620. return request
  621. }
  622. // buildFilterFromParams creates a filter from individual CloudCostQuery parameters
  623. func (s *MCPServer) buildFilterFromParams(params *CloudCostQuery) filter.Filter {
  624. var filterParts []string
  625. // Add provider filter
  626. if params.Provider != "" {
  627. filterParts = append(filterParts, fmt.Sprintf(`provider:"%s"`, params.Provider))
  628. }
  629. // Add providerID filter
  630. if params.ProviderID != "" {
  631. filterParts = append(filterParts, fmt.Sprintf(`providerID:"%s"`, params.ProviderID))
  632. }
  633. // Add service filter
  634. if params.Service != "" {
  635. filterParts = append(filterParts, fmt.Sprintf(`service:"%s"`, params.Service))
  636. }
  637. // Add category filter
  638. if params.Category != "" {
  639. filterParts = append(filterParts, fmt.Sprintf(`category:"%s"`, params.Category))
  640. }
  641. // Region is intentionally not supported here
  642. // Add account filter (maps to accountID)
  643. if params.AccountID != "" {
  644. filterParts = append(filterParts, fmt.Sprintf(`accountID:"%s"`, params.AccountID))
  645. }
  646. // Add invoiceEntityID filter
  647. if params.InvoiceEntityID != "" {
  648. filterParts = append(filterParts, fmt.Sprintf(`invoiceEntityID:"%s"`, params.InvoiceEntityID))
  649. }
  650. // Add label filters (label[key]:"value")
  651. if len(params.Labels) > 0 {
  652. for k, v := range params.Labels {
  653. if k == "" {
  654. continue
  655. }
  656. filterParts = append(filterParts, fmt.Sprintf(`label[%s]:"%s"`, k, v))
  657. }
  658. }
  659. // If no filters specified, return nil
  660. if len(filterParts) == 0 {
  661. return nil
  662. }
  663. // Combine all filter parts with AND logic (parser expects 'and')
  664. filterString := strings.Join(filterParts, " and ")
  665. // Parse the combined filter string
  666. parser := cloudcostfilter.NewCloudCostFilterParser()
  667. filter, err := parser.Parse(filterString)
  668. if err != nil {
  669. // Log error but return nil rather than failing
  670. fmt.Printf("Warning: failed to parse combined filter '%s': %v\n", filterString, err)
  671. return nil
  672. }
  673. return filter
  674. }
  675. // transformCloudCostSetRange converts a opencost.CloudCostSetRange into the MCP's CloudCostResponse format.
  676. func transformCloudCostSetRange(ccsr *opencost.CloudCostSetRange) *CloudCostResponse {
  677. if ccsr == nil || len(ccsr.CloudCostSets) == 0 {
  678. return &CloudCostResponse{
  679. CloudCosts: make(map[string]*CloudCostSet),
  680. Summary: &CloudCostSummary{
  681. TotalNetCost: 0,
  682. },
  683. }
  684. }
  685. mcpCloudCosts := make(map[string]*CloudCostSet)
  686. var totalNetCost, totalAmortizedCost, totalInvoicedCost float64
  687. providerBreakdown := make(map[string]float64)
  688. serviceBreakdown := make(map[string]float64)
  689. regionBreakdown := make(map[string]float64)
  690. // Process each cloud cost set in the range
  691. for i, ccSet := range ccsr.CloudCostSets {
  692. if ccSet == nil {
  693. continue
  694. }
  695. setName := fmt.Sprintf("cloudcosts_%d", i)
  696. mcpSet := &CloudCostSet{
  697. Name: setName,
  698. CloudCosts: []*CloudCost{},
  699. AggregationProperties: ccSet.AggregationProperties,
  700. Window: &TimeWindow{
  701. Start: *ccSet.Window.Start(),
  702. End: *ccSet.Window.End(),
  703. },
  704. }
  705. // Convert each cloud cost item
  706. for _, item := range ccSet.CloudCosts {
  707. if item == nil {
  708. continue
  709. }
  710. mcpCC := &CloudCost{
  711. Properties: CloudCostProperties{
  712. ProviderID: item.Properties.ProviderID,
  713. Provider: item.Properties.Provider,
  714. AccountID: item.Properties.AccountID,
  715. AccountName: item.Properties.AccountName,
  716. InvoiceEntityID: item.Properties.InvoiceEntityID,
  717. InvoiceEntityName: item.Properties.InvoiceEntityName,
  718. RegionID: item.Properties.RegionID,
  719. AvailabilityZone: item.Properties.AvailabilityZone,
  720. Service: item.Properties.Service,
  721. Category: item.Properties.Category,
  722. Labels: item.Properties.Labels,
  723. },
  724. Window: TimeWindow{
  725. Start: *item.Window.Start(),
  726. End: *item.Window.End(),
  727. },
  728. ListCost: CostMetric{
  729. Cost: item.ListCost.Cost,
  730. KubernetesPercent: item.ListCost.KubernetesPercent,
  731. },
  732. NetCost: CostMetric{
  733. Cost: item.NetCost.Cost,
  734. KubernetesPercent: item.NetCost.KubernetesPercent,
  735. },
  736. AmortizedNetCost: CostMetric{
  737. Cost: item.AmortizedNetCost.Cost,
  738. KubernetesPercent: item.AmortizedNetCost.KubernetesPercent,
  739. },
  740. InvoicedCost: CostMetric{
  741. Cost: item.InvoicedCost.Cost,
  742. KubernetesPercent: item.InvoicedCost.KubernetesPercent,
  743. },
  744. AmortizedCost: CostMetric{
  745. Cost: item.AmortizedCost.Cost,
  746. KubernetesPercent: item.AmortizedCost.KubernetesPercent,
  747. },
  748. }
  749. mcpSet.CloudCosts = append(mcpSet.CloudCosts, mcpCC)
  750. // Update summary totals
  751. totalNetCost += item.NetCost.Cost
  752. totalAmortizedCost += item.AmortizedNetCost.Cost
  753. totalInvoicedCost += item.InvoicedCost.Cost
  754. // Update breakdowns
  755. providerBreakdown[item.Properties.Provider] += item.NetCost.Cost
  756. serviceBreakdown[item.Properties.Service] += item.NetCost.Cost
  757. regionBreakdown[item.Properties.RegionID] += item.NetCost.Cost
  758. }
  759. mcpCloudCosts[setName] = mcpSet
  760. }
  761. // Calculate cost-weighted average Kubernetes percentage (by NetCost)
  762. var avgKubernetesPercent float64
  763. var numerator, denominator float64
  764. for _, ccSet := range ccsr.CloudCostSets {
  765. for _, item := range ccSet.CloudCosts {
  766. if item == nil {
  767. continue
  768. }
  769. cost := item.NetCost.Cost
  770. percent := item.NetCost.KubernetesPercent
  771. if cost <= 0 {
  772. continue
  773. }
  774. numerator += cost * percent
  775. denominator += cost
  776. }
  777. }
  778. if denominator > 0 {
  779. avgKubernetesPercent = numerator / denominator
  780. }
  781. summary := &CloudCostSummary{
  782. TotalNetCost: totalNetCost,
  783. TotalAmortizedCost: totalAmortizedCost,
  784. TotalInvoicedCost: totalInvoicedCost,
  785. KubernetesPercent: avgKubernetesPercent,
  786. ProviderBreakdown: providerBreakdown,
  787. ServiceBreakdown: serviceBreakdown,
  788. RegionBreakdown: regionBreakdown,
  789. }
  790. return &CloudCostResponse{
  791. CloudCosts: mcpCloudCosts,
  792. Summary: summary,
  793. }
  794. }